<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><div id="myscoll"></div><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>JDBC | XiaoFei🥝</title><meta name="keywords" content="JDBC"><meta name="author" content="XiaoFei🥝"><meta name="copyright" content="XiaoFei🥝"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="JDBC">
<meta property="og:type" content="article">
<meta property="og:title" content="JDBC">
<meta property="og:url" content="https://www.naste.top:1024/posts/2414116852.html">
<meta property="og:site_name" content="XiaoFei🥝">
<meta property="og:description" content="JDBC">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.naste.top:9000/webp/1515952743784.webp">
<meta property="article:published_time" content="2022-06-09T10:01:02.000Z">
<meta property="article:modified_time" content="2024-04-26T09:52:18.015Z">
<meta property="article:author" content="XiaoFei🥝">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="JDBC">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.naste.top:9000/webp/1515952743784.webp"><link rel="shortcut icon" href="/"><link rel="canonical" href="https://www.naste.top:1024/posts/2414116852"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.json","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JDBC',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-04-26 17:52:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://cdn1.tianli0.top/npm/element-ui@2.15.6/packages/theme-chalk/lib/index.css"><style id="themeColor"></style><style id="rightSide"></style><style id="transPercent"></style><style id="blurNum"></style><style id="settingStyle"></style><span id="fps"></span><style id="defineBg"></style><style id="menu_shadow"></style><svg aria-hidden="true" style="position:absolute; overflow:hidden; width:0; height:0"><symbol id="icon-sun" viewBox="0 0 1024 1024"><path d="M960 512l-128 128v192h-192l-128 128-128-128H192v-192l-128-128 128-128V192h192l128-128 128 128h192v192z" fill="#FFD878" p-id="8420"></path><path d="M736 512a224 224 0 1 0-448 0 224 224 0 1 0 448 0z" fill="#FFE4A9" p-id="8421"></path><path d="M512 109.248L626.752 224H800v173.248L914.752 512 800 626.752V800h-173.248L512 914.752 397.248 800H224v-173.248L109.248 512 224 397.248V224h173.248L512 109.248M512 64l-128 128H192v192l-128 128 128 128v192h192l128 128 128-128h192v-192l128-128-128-128V192h-192l-128-128z" fill="#4D5152" p-id="8422"></path><path d="M512 320c105.888 0 192 86.112 192 192s-86.112 192-192 192-192-86.112-192-192 86.112-192 192-192m0-32a224 224 0 1 0 0 448 224 224 0 0 0 0-448z" fill="#4D5152" p-id="8423"></path></symbol><symbol id="icon-moon" viewBox="0 0 1024 1024"><path d="M611.370667 167.082667a445.013333 445.013333 0 0 1-38.4 161.834666 477.824 477.824 0 0 1-244.736 244.394667 445.141333 445.141333 0 0 1-161.109334 38.058667 85.077333 85.077333 0 0 0-65.066666 135.722666A462.08 462.08 0 1 0 747.093333 102.058667a85.077333 85.077333 0 0 0-135.722666 65.024z" fill="#FFB531" p-id="11345"></path><path d="M329.728 274.133333l35.157333-35.157333a21.333333 21.333333 0 1 0-30.165333-30.165333l-35.157333 35.157333-35.114667-35.157333a21.333333 21.333333 0 0 0-30.165333 30.165333l35.114666 35.157333-35.114666 35.157334a21.333333 21.333333 0 1 0 30.165333 30.165333l35.114667-35.157333 35.157333 35.157333a21.333333 21.333333 0 1 0 30.165333-30.165333z" fill="#030835" p-id="11346"></path></symbol></svg><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="XiaoFei🥝" type="application/atom+xml">
</head><body><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" onerror="onerror=null;src='/assets/r1.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">149</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">99</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">46</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">XiaoFei🥝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div><center id="name-container"><a id="page-name" href="javascript:scrollToTop()">PAGE_NAME</a></center><div id="nav-right"><div id="search-button"><a class="search faa-parent animated-hover" title="检索站内任何你想要的信息"><svg class="faa-tada icon" style="height:24px;width:24px;fill:currentColor;position:relative;top:6px" aria-hidden="true"><use xlink:href="#icon-valentine_-search-love-find-heart"></use></svg><span> 搜索</span></a></div><a class="meihua faa-parent animated-hover" onclick="toggleWinbox()" title="美化设置-自定义你的风格" id="meihua-button"><svg class="faa-tada icon" style="height:26px;width:26px;fill:currentColor;position:relative;top:8px" aria-hidden="true"><use xlink:href="#icon-tupian1"></use></svg></a><a class="sun_moon faa-parent animated-hover" onclick="switchNightMode()" title="浅色和深色模式转换" id="nightmode-button"><svg class="faa-tada" style="height:25px;width:25px;fill:currentColor;position:relative;top:7px" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon">       </use></svg></a><div id="toggle-menu"><a><i class="fas fa-bars fa-fw"></i></a></div></div></div></nav><div id="post-info"><h1 class="post-title">JDBC</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><svg class="meta_icon post-meta-icon" style="width:30px;height:30px;position:relative;top:10px"><use xlink:href="#icon-rili"></use></svg><span class="post-meta-label">发表于 </span><time class="post-meta-date-created" datetime="2022-06-09T10:01:02.000Z" title="发表于 2022-06-09 18:01:02">2022-06-09</time><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-gengxin1"></use></svg><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-04-26T09:52:18.015Z" title="更新于 2024-04-26 17:52:18">2024-04-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right post-meta-separator"></i><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/Java/JDBC/">JDBC</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:8px"><use xlink:href="#icon-charuword"></use></svg><span class="post-meta-label">字数总计:</span><span class="word-count">1.5w</span><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:20px;height:20px;position:relative;top:5px"><use xlink:href="#icon-shizhong"></use></svg><span class="post-meta-label">阅读时长:</span><span>59分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JDBC"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:5px"><use xlink:href="#icon-eye"></use></svg><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M -160 44 c 30 0 58 -18 88 -18 s 58 18 88 18 s 58 -18 88 -18 s 58 18 88 18 v 44 h -352 Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="JDBC核心技术"><a href="#JDBC核心技术" class="headerlink" title="JDBC核心技术"></a>JDBC核心技术</h1><h2 id="第1章：JDBC概述"><a href="#第1章：JDBC概述" class="headerlink" title="第1章：JDBC概述"></a>第1章：JDBC概述</h2><h3 id="1-1-数据的持久化"><a href="#1-1-数据的持久化" class="headerlink" title="1.1 数据的持久化"></a>1.1 数据的持久化</h3><ul>
<li><p>持久化(persistence)：<strong>把数据保存到可掉电式存储设备中以供之后使用</strong>。大多数情况下，特别是企业级应用，<strong>数据持久化意味着将内存中的数据保存到硬盘</strong>上加以”固化”<strong>，而持久化的实现过程大多通过各种关系数据库来完成</strong>。</p>
</li>
<li><p>持久化的主要应用是将内存中的数据存储在关系型数据库中，当然也可以存储在磁盘文件、XML数据文件中。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566741430592.webp" alt="1566741430592"> </p>
</li>
</ul>
<h3 id="1-2-Java中的数据存储技术"><a href="#1-2-Java中的数据存储技术" class="headerlink" title="1.2 Java中的数据存储技术"></a>1.2 Java中的数据存储技术</h3><ul>
<li><p>在Java中，数据库存取技术可分为如下几类：</p>
<ul>
<li><strong>JDBC</strong>直接访问数据库</li>
<li><p>JDO (Java Data Object )技术</p>
</li>
<li><p><strong>第三方O/R工具</strong>，如Hibernate, Mybatis 等</p>
</li>
</ul>
</li>
<li><p>JDBC是java访问数据库的基石，JDO、Hibernate、MyBatis等只是更好的封装了JDBC。</p>
</li>
</ul>
<h3 id="1-3-JDBC介绍"><a href="#1-3-JDBC介绍" class="headerlink" title="1.3 JDBC介绍"></a>1.3 JDBC介绍</h3><ul>
<li>JDBC(Java Database Connectivity)是一个<strong>独立于特定数据库管理系统、通用的SQL数据库存取和操作的公共接口</strong>（一组API），定义了用来访问数据库的标准Java类库，（<strong>java.sql,javax.sql</strong>）使用这些类库可以以一种<strong>标准</strong>的方法、方便地访问数据库资源。</li>
<li>JDBC为访问不同的数据库提供了一种<strong>统一的途径</strong>，为开发者屏蔽了一些细节问题。</li>
<li>JDBC的目标是使Java程序员使用JDBC可以连接任何<strong>提供了JDBC驱动程序</strong>的数据库系统，这样就使得程序员无需对特定的数据库系统的特点有过多的了解，从而大大简化和加快了开发过程。</li>
<li>如果没有JDBC，那么Java程序访问数据库时是这样的：</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555575760234.webp" alt="1555575760234"></p>
<hr>
<ul>
<li>有了JDBC，Java程序访问数据库时是这样的：</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555575981203.webp" alt="1555575981203"></p>
<hr>
<ul>
<li>总结如下：</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566741692804.webp" alt="1566741692804"></p>
<h3 id="1-4-JDBC体系结构"><a href="#1-4-JDBC体系结构" class="headerlink" title="1.4 JDBC体系结构"></a>1.4 JDBC体系结构</h3><ul>
<li>JDBC接口（API）包括两个层次：<ul>
<li><strong>面向应用的API</strong>：Java API，抽象接口，供应用程序开发人员使用（连接数据库，执行SQL语句，获得结果）。</li>
<li><strong>面向数据库的API</strong>：Java Driver API，供开发商开发数据库驱动程序用。</li>
</ul>
</li>
</ul>
<blockquote>
<p><strong>JDBC是sun公司提供一套用于数据库操作的接口，java程序员只需要面向这套接口编程即可。</strong></p>
<p><strong>不同的数据库厂商，需要针对这套接口，提供不同实现。不同的实现的集合，即为不同数据库的驱动。                                                                ————面向接口编程</strong></p>
</blockquote>
<h3 id="1-5-JDBC程序编写步骤"><a href="#1-5-JDBC程序编写步骤" class="headerlink" title="1.5 JDBC程序编写步骤"></a>1.5 JDBC程序编写步骤</h3><p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1565969323908.webp" alt="1565969323908"></p>
<blockquote>
<p>补充：ODBC(<strong>Open Database Connectivity</strong>，开放式数据库连接)，是微软在Windows平台下推出的。使用者在程序中只需要调用ODBC API，由 ODBC 驱动程序将调用转换成为对特定的数据库的调用请求。</p>
</blockquote>
<h2 id="第2章：获取数据库连接"><a href="#第2章：获取数据库连接" class="headerlink" title="第2章：获取数据库连接"></a>第2章：获取数据库连接</h2><h3 id="2-1-要素一：Driver接口实现类"><a href="#2-1-要素一：Driver接口实现类" class="headerlink" title="2.1 要素一：Driver接口实现类"></a>2.1 要素一：Driver接口实现类</h3><h4 id="2-1-1-Driver接口介绍"><a href="#2-1-1-Driver接口介绍" class="headerlink" title="2.1.1 Driver接口介绍"></a>2.1.1 Driver接口介绍</h4><ul>
<li><p>java.sql.Driver 接口是所有 JDBC 驱动程序需要实现的接口。这个接口是提供给数据库厂商使用的，不同数据库厂商提供不同的实现。</p>
</li>
<li><p>在程序中不需要直接去访问实现了 Driver 接口的类，而是由驱动程序管理器类(java.sql.DriverManager)去调用这些Driver实现。</p>
<ul>
<li>Oracle的驱动：<strong>oracle.jdbc.driver.OracleDriver</strong></li>
<li>mySql的驱动： <strong>com.mysql.jdbc.Driver</strong></li>
</ul>
</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555576157618.webp" alt="1555576157618"></p>
<ul>
<li><p>将上述jar包拷贝到Java工程的一个目录中，习惯上新建一个lib文件夹。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566134718955.webp" alt="1566134718955"></p>
</li>
</ul>
<p>在驱动jar上右键—&gt;Build Path—&gt;Add to Build Path</p>
<p>注意：如果是Dynamic Web Project（动态的web项目）话，则是把驱动jar放到WebContent（有的开发工具叫WebRoot）目录中的WEB-INF目录中的lib目录下即可</p>
<p> <img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566135290460.webp" alt="1566135290460"></p>
<h4 id="2-1-2-加载与注册JDBC驱动"><a href="#2-1-2-加载与注册JDBC驱动" class="headerlink" title="2.1.2 加载与注册JDBC驱动"></a>2.1.2 加载与注册JDBC驱动</h4><ul>
<li><p>加载驱动：加载 JDBC 驱动需调用 Class 类的静态方法 forName()，向其传递要加载的 JDBC 驱动的类名</p>
<ul>
<li><strong>Class.forName(“com.mysql.jdbc.Driver”);</strong></li>
</ul>
</li>
<li><p>注册驱动：DriverManager 类是驱动程序管理器类，负责管理驱动程序</p>
<ul>
<li><p><strong>使用DriverManager.registerDriver(com.mysql.jdbc.Driver)来注册驱动</strong></p>
</li>
<li><p>通常不用显式调用 DriverManager 类的 registerDriver() 方法来注册驱动程序类的实例，因为 Driver 接口的驱动程序类<strong>都</strong>包含了静态代码块，在这个静态代码块中，会调用 DriverManager.registerDriver() 方法来注册自身的一个实例。下图是MySQL的Driver实现类的源码：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566136831283.webp" alt="1566136831283"></p>
</li>
</ul>
</li>
</ul>
<h3 id="2-2-要素二：URL"><a href="#2-2-要素二：URL" class="headerlink" title="2.2 要素二：URL"></a>2.2 要素二：URL</h3><ul>
<li><p>JDBC URL 用于标识一个被注册的驱动程序，驱动程序管理器通过这个 URL 选择正确的驱动程序，从而建立到数据库的连接。</p>
</li>
<li><p>JDBC URL的标准由三部分组成，各部分间用冒号分隔。 </p>
<ul>
<li><strong>jdbc:子协议:子名称</strong></li>
<li><strong>协议</strong>：JDBC URL中的协议总是jdbc </li>
<li><strong>子协议</strong>：子协议用于标识一个数据库驱动程序</li>
<li><strong>子名称</strong>：一种标识数据库的方法。子名称可以依不同的子协议而变化，用子名称的目的是为了<strong>定位数据库</strong>提供足够的信息。包含<strong>主机名</strong>(对应服务端的ip地址)<strong>，端口号，数据库名</strong></li>
</ul>
</li>
<li><p>举例：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555576477107.webp" alt="1555576477107"></p>
</li>
<li><p><strong>几种常用数据库的 JDBC URL</strong></p>
<ul>
<li><p>MySQL的连接URL编写方式：</p>
<ul>
<li>jdbc:mysql://主机名称:mysql服务端口号/数据库名称?参数=值&amp;参数=值</li>
<li>jdbc:mysql://localhost:3306/atguigu</li>
<li>jdbc:mysql://localhost:3306/atguigu<strong>?useUnicode=true&amp;characterEncoding=utf8</strong>（如果JDBC程序与服务器端的字符集不一致，会导致乱码，那么可以通过参数指定服务器端的字符集）</li>
<li>jdbc:mysql://localhost:3306/atguigu?user=root&amp;password=123456</li>
</ul>
</li>
<li><p>Oracle 9i的连接URL编写方式：</p>
<ul>
<li>jdbc:oracle:thin:@主机名称:oracle服务端口号:数据库名称</li>
<li>jdbc:oracle:thin:@localhost:1521:atguigu</li>
</ul>
</li>
<li><p>SQLServer的连接URL编写方式：</p>
<ul>
<li><p>jdbc:sqlserver://主机名称:sqlserver服务端口号:DatabaseName=数据库名称</p>
</li>
<li><p>jdbc:sqlserver://localhost:1433:DatabaseName=atguigu</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="2-3-要素三：用户名和密码"><a href="#2-3-要素三：用户名和密码" class="headerlink" title="2.3 要素三：用户名和密码"></a>2.3 要素三：用户名和密码</h3><ul>
<li>user,password可以用“属性名=属性值”方式告诉数据库</li>
<li>可以调用 DriverManager 类的 getConnection() 方法建立到数据库的连接</li>
</ul>
<h3 id="2-4-数据库连接方式举例"><a href="#2-4-数据库连接方式举例" class="headerlink" title="2.4 数据库连接方式举例"></a>2.4 数据库连接方式举例</h3><h4 id="2-4-1-连接方式一"><a href="#2-4-1-连接方式一" class="headerlink" title="2.4.1 连接方式一"></a>2.4.1 连接方式一</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testConnection1</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//1.提供java.sql.Driver接口实现类的对象</span></span><br><span class="line">           <span class="type">Driver</span> <span class="variable">driver</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">           driver = <span class="keyword">new</span> <span class="title class_">com</span>.mysql.jdbc.Driver();</span><br><span class="line"></span><br><span class="line">           <span class="comment">//2.提供url，指明具体操作的数据</span></span><br><span class="line">           <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> <span class="string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>;</span><br><span class="line"></span><br><span class="line">           <span class="comment">//3.提供Properties的对象，指明用户名和密码</span></span><br><span class="line">           <span class="type">Properties</span> <span class="variable">info</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">           info.setProperty(<span class="string">&quot;user&quot;</span>, <span class="string">&quot;root&quot;</span>);</span><br><span class="line">           info.setProperty(<span class="string">&quot;password&quot;</span>, <span class="string">&quot;abc123&quot;</span>);</span><br><span class="line"></span><br><span class="line">           <span class="comment">//4.调用driver的connect()，获取连接</span></span><br><span class="line">           <span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> driver.connect(url, info);</span><br><span class="line">           System.out.println(conn);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：上述代码中显式出现了第三方数据库的API</p>
</blockquote>
<h4 id="2-4-2-连接方式二"><a href="#2-4-2-连接方式二" class="headerlink" title="2.4.2 连接方式二"></a>2.4.2 连接方式二</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testConnection2</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//1.实例化Driver</span></span><br><span class="line">           <span class="type">String</span> <span class="variable">className</span> <span class="operator">=</span> <span class="string">&quot;com.mysql.jdbc.Driver&quot;</span>;</span><br><span class="line">           <span class="type">Class</span> <span class="variable">clazz</span> <span class="operator">=</span> Class.forName(className);</span><br><span class="line">           <span class="type">Driver</span> <span class="variable">driver</span> <span class="operator">=</span> (Driver) clazz.newInstance();</span><br><span class="line"></span><br><span class="line">           <span class="comment">//2.提供url，指明具体操作的数据</span></span><br><span class="line">           <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> <span class="string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>;</span><br><span class="line"></span><br><span class="line">           <span class="comment">//3.提供Properties的对象，指明用户名和密码</span></span><br><span class="line">           <span class="type">Properties</span> <span class="variable">info</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">           info.setProperty(<span class="string">&quot;user&quot;</span>, <span class="string">&quot;root&quot;</span>);</span><br><span class="line">           info.setProperty(<span class="string">&quot;password&quot;</span>, <span class="string">&quot;abc123&quot;</span>);</span><br><span class="line"></span><br><span class="line">           <span class="comment">//4.调用driver的connect()，获取连接</span></span><br><span class="line">           <span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> driver.connect(url, info);</span><br><span class="line">           System.out.println(conn);</span><br><span class="line"></span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：相较于方式一，这里使用反射实例化Driver，不在代码中体现第三方数据库的API。体现了面向接口编程思想。</p>
</blockquote>
<h4 id="2-4-3-连接方式三"><a href="#2-4-3-连接方式三" class="headerlink" title="2.4.3 连接方式三"></a>2.4.3 连接方式三</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testConnection3</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//1.数据库连接的4个基本要素：</span></span><br><span class="line">           <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> <span class="string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>;</span><br><span class="line">           <span class="type">String</span> <span class="variable">user</span> <span class="operator">=</span> <span class="string">&quot;root&quot;</span>;</span><br><span class="line">           <span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> <span class="string">&quot;abc123&quot;</span>;</span><br><span class="line">           <span class="type">String</span> <span class="variable">driverName</span> <span class="operator">=</span> <span class="string">&quot;com.mysql.jdbc.Driver&quot;</span>;</span><br><span class="line"></span><br><span class="line">           <span class="comment">//2.实例化Driver</span></span><br><span class="line">           <span class="type">Class</span> <span class="variable">clazz</span> <span class="operator">=</span> Class.forName(driverName);</span><br><span class="line">           <span class="type">Driver</span> <span class="variable">driver</span> <span class="operator">=</span> (Driver) clazz.newInstance();</span><br><span class="line">           <span class="comment">//3.注册驱动</span></span><br><span class="line">           DriverManager.registerDriver(driver);</span><br><span class="line">           <span class="comment">//4.获取连接</span></span><br><span class="line">           <span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> DriverManager.getConnection(url, user, password);</span><br><span class="line">           System.out.println(conn);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：使用DriverManager实现数据库的连接。体会获取连接必要的4个基本要素。</p>
</blockquote>
<h4 id="2-4-4-连接方式四"><a href="#2-4-4-连接方式四" class="headerlink" title="2.4.4 连接方式四"></a>2.4.4 连接方式四</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testConnection4</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//1.数据库连接的4个基本要素：</span></span><br><span class="line">           <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> <span class="string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>;</span><br><span class="line">           <span class="type">String</span> <span class="variable">user</span> <span class="operator">=</span> <span class="string">&quot;root&quot;</span>;</span><br><span class="line">           <span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> <span class="string">&quot;abc123&quot;</span>;</span><br><span class="line">           <span class="type">String</span> <span class="variable">driverName</span> <span class="operator">=</span> <span class="string">&quot;com.mysql.jdbc.Driver&quot;</span>;</span><br><span class="line"></span><br><span class="line">           <span class="comment">//2.加载驱动 （①实例化Driver ②注册驱动）</span></span><br><span class="line">           Class.forName(driverName);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">           <span class="comment">//Driver driver = (Driver) clazz.newInstance();</span></span><br><span class="line">           <span class="comment">//3.注册驱动</span></span><br><span class="line">           <span class="comment">//DriverManager.registerDriver(driver);</span></span><br><span class="line">           <span class="comment">/*</span></span><br><span class="line"><span class="comment">           可以注释掉上述代码的原因，是因为在mysql的Driver类中声明有：</span></span><br><span class="line"><span class="comment">           static &#123;</span></span><br><span class="line"><span class="comment">               try &#123;</span></span><br><span class="line"><span class="comment">                   DriverManager.registerDriver(new Driver());</span></span><br><span class="line"><span class="comment">               &#125; catch (SQLException var1) &#123;</span></span><br><span class="line"><span class="comment">                   throw new RuntimeException(&quot;Can&#x27;t register driver!&quot;);</span></span><br><span class="line"><span class="comment">               &#125;</span></span><br><span class="line"><span class="comment">           &#125;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">            */</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">           <span class="comment">//3.获取连接</span></span><br><span class="line">           <span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> DriverManager.getConnection(url, user, password);</span><br><span class="line">           System.out.println(conn);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：不必显式的注册驱动了。因为在DriverManager的源码中已经存在静态代码块，实现了驱动的注册。</p>
</blockquote>
<h4 id="2-4-5-连接方式五-最终版"><a href="#2-4-5-连接方式五-最终版" class="headerlink" title="2.4.5 连接方式五(最终版)"></a>2.4.5 连接方式五(最终版)</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span>  <span class="keyword">void</span> <span class="title function_">testConnection5</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">   	<span class="comment">//1.加载配置文件</span></span><br><span class="line">       <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> ConnectionTest.class.getClassLoader().getResourceAsStream(<span class="string">&quot;jdbc.properties&quot;</span>);</span><br><span class="line">       <span class="type">Properties</span> <span class="variable">pros</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">       pros.load(is);</span><br><span class="line">       </span><br><span class="line">       <span class="comment">//2.读取配置信息</span></span><br><span class="line">       <span class="type">String</span> <span class="variable">user</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;user&quot;</span>);</span><br><span class="line">       <span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;password&quot;</span>);</span><br><span class="line">       <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;url&quot;</span>);</span><br><span class="line">       <span class="type">String</span> <span class="variable">driverClass</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;driverClass&quot;</span>);</span><br><span class="line"></span><br><span class="line">       <span class="comment">//3.加载驱动</span></span><br><span class="line">       Class.forName(driverClass);</span><br><span class="line"></span><br><span class="line">       <span class="comment">//4.获取连接</span></span><br><span class="line">       <span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> DriverManager.getConnection(url,user,password);</span><br><span class="line">       System.out.println(conn);</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>其中，配置文件声明在工程的src目录下：【jdbc.properties】</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">user</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">password</span>=<span class="string">abc123</span></span><br><span class="line"><span class="attr">url</span>=<span class="string">jdbc:mysql://localhost:3306/test</span></span><br><span class="line"><span class="attr">driverClass</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：使用配置文件的方式保存配置信息，在代码中加载配置文件</p>
<p><strong>使用配置文件的好处：</strong></p>
<p>①实现了代码和数据的分离，如果需要修改配置信息，直接在配置文件中修改，不需要深入代码<br>②如果修改了配置信息，省去重新编译的过程。</p>
</blockquote>
<h2 id="第3章：使用PreparedStatement实现CRUD操作"><a href="#第3章：使用PreparedStatement实现CRUD操作" class="headerlink" title="第3章：使用PreparedStatement实现CRUD操作"></a>第3章：使用PreparedStatement实现CRUD操作</h2><h3 id="3-1-操作和访问数据库"><a href="#3-1-操作和访问数据库" class="headerlink" title="3.1 操作和访问数据库"></a>3.1 操作和访问数据库</h3><ul>
<li><p>数据库连接被用于向数据库服务器发送命令和 SQL 语句，并接受数据库服务器返回的结果。其实一个数据库连接就是一个Socket连接。</p>
</li>
<li><p>在 java.sql 包中有 3 个接口分别定义了对数据库的调用的不同方式：</p>
<ul>
<li>Statement：用于执行静态 SQL 语句并返回它所生成结果的对象。 </li>
<li>PrepatedStatement：SQL 语句被预编译并存储在此对象中，可以使用此对象多次高效地执行该语句。</li>
<li>CallableStatement：用于执行 SQL 存储过程</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566573842140.webp" alt="1566573842140"></p>
</li>
</ul>
<h3 id="3-2-使用Statement操作数据表的弊端"><a href="#3-2-使用Statement操作数据表的弊端" class="headerlink" title="3.2 使用Statement操作数据表的弊端"></a>3.2 使用Statement操作数据表的弊端</h3><ul>
<li><p>通过调用 Connection 对象的 createStatement() 方法创建该对象。该对象用于执行静态的 SQL 语句，并且返回执行结果。</p>
</li>
<li><p>Statement 接口中定义了下列方法用于执行 SQL 语句：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> excuteUpdate(String <span class="keyword">sql</span>)：执行更新操作<span class="keyword">INSERT</span>、<span class="keyword">UPDATE</span>、<span class="keyword">DELETE</span></span><br><span class="line">ResultSet executeQuery(String <span class="keyword">sql</span>)：执行查询操作<span class="keyword">SELECT</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>但是使用Statement操作数据表存在弊端：</p>
<ul>
<li><strong>问题一：存在拼串操作，繁琐</strong></li>
<li><strong>问题二：存在SQL注入问题</strong></li>
</ul>
</li>
<li><p>SQL 注入是利用某些系统没有对用户输入的数据进行充分的检查，而在用户输入数据中注入非法的 SQL 语句段或命令(如：SELECT user, password FROM user_table WHERE user=’a’ OR 1 = ‘ AND password = ‘ OR ‘1’ = ‘1’) ，从而利用系统的 SQL 引擎完成恶意行为的做法。</p>
</li>
<li><p>对于 Java 而言，要防范 SQL 注入，只要用 PreparedStatement(从Statement扩展而来) 取代 Statement 就可以了。</p>
</li>
<li><p>代码演示：</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StatementTest</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 使用Statement的弊端：需要拼写sql语句，并且存在SQL注入的问题</span></span><br><span class="line">	<span class="meta">@Test</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testLogin</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="type">Scanner</span> <span class="variable">scan</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line"></span><br><span class="line">		System.out.print(<span class="string">&quot;用户名：&quot;</span>);</span><br><span class="line">		<span class="type">String</span> <span class="variable">userName</span> <span class="operator">=</span> scan.nextLine();</span><br><span class="line">		System.out.print(<span class="string">&quot;密   码：&quot;</span>);</span><br><span class="line">		<span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> scan.nextLine();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// SELECT user,password FROM user_table WHERE USER = &#x27;1&#x27; or &#x27; AND PASSWORD = &#x27;=&#x27;1&#x27; or &#x27;1&#x27; = &#x27;1&#x27;;</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;SELECT user,password FROM user_table WHERE USER = &#x27;&quot;</span> + userName + <span class="string">&quot;&#x27; AND PASSWORD = &#x27;&quot;</span> + password</span><br><span class="line">				+ <span class="string">&quot;&#x27;&quot;</span>;</span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> get(sql, User.class);</span><br><span class="line">		<span class="keyword">if</span> (user != <span class="literal">null</span>) &#123;</span><br><span class="line">			System.out.println(<span class="string">&quot;登陆成功!&quot;</span>);</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			System.out.println(<span class="string">&quot;用户名或密码错误！&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 使用Statement实现对数据表的查询操作</span></span><br><span class="line">	<span class="keyword">public</span> &lt;T&gt; T <span class="title function_">get</span><span class="params">(String sql, Class&lt;T&gt; clazz)</span> &#123;</span><br><span class="line">		<span class="type">T</span> <span class="variable">t</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">		<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="type">Statement</span> <span class="variable">st</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="type">ResultSet</span> <span class="variable">rs</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// 1.加载配置文件</span></span><br><span class="line">			<span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> StatementTest.class.getClassLoader().getResourceAsStream(<span class="string">&quot;jdbc.properties&quot;</span>);</span><br><span class="line">			<span class="type">Properties</span> <span class="variable">pros</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">			pros.load(is);</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 2.读取配置信息</span></span><br><span class="line">			<span class="type">String</span> <span class="variable">user</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;user&quot;</span>);</span><br><span class="line">			<span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;password&quot;</span>);</span><br><span class="line">			<span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;url&quot;</span>);</span><br><span class="line">			<span class="type">String</span> <span class="variable">driverClass</span> <span class="operator">=</span> pros.getProperty(<span class="string">&quot;driverClass&quot;</span>);</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 3.加载驱动</span></span><br><span class="line">			Class.forName(driverClass);</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 4.获取连接</span></span><br><span class="line">			conn = DriverManager.getConnection(url, user, password);</span><br><span class="line"></span><br><span class="line">			st = conn.createStatement();</span><br><span class="line"></span><br><span class="line">			rs = st.executeQuery(sql);</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 获取结果集的元数据</span></span><br><span class="line">			<span class="type">ResultSetMetaData</span> <span class="variable">rsmd</span> <span class="operator">=</span> rs.getMetaData();</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 获取结果集的列数</span></span><br><span class="line">			<span class="type">int</span> <span class="variable">columnCount</span> <span class="operator">=</span> rsmd.getColumnCount();</span><br><span class="line"></span><br><span class="line">			<span class="keyword">if</span> (rs.next()) &#123;</span><br><span class="line"></span><br><span class="line">				t = clazz.newInstance();</span><br><span class="line"></span><br><span class="line">				<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; columnCount; i++) &#123;</span><br><span class="line">					<span class="comment">// //1. 获取列的名称</span></span><br><span class="line">					<span class="comment">// String columnName = rsmd.getColumnName(i+1);</span></span><br><span class="line"></span><br><span class="line">					<span class="comment">// 1. 获取列的别名</span></span><br><span class="line">					<span class="type">String</span> <span class="variable">columnName</span> <span class="operator">=</span> rsmd.getColumnLabel(i + <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">					<span class="comment">// 2. 根据列名获取对应数据表中的数据</span></span><br><span class="line">					<span class="type">Object</span> <span class="variable">columnVal</span> <span class="operator">=</span> rs.getObject(columnName);</span><br><span class="line"></span><br><span class="line">					<span class="comment">// 3. 将数据表中得到的数据，封装进对象</span></span><br><span class="line">					<span class="type">Field</span> <span class="variable">field</span> <span class="operator">=</span> clazz.getDeclaredField(columnName);</span><br><span class="line">					field.setAccessible(<span class="literal">true</span>);</span><br><span class="line">					field.set(t, columnVal);</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">return</span> t;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">			<span class="comment">// 关闭资源</span></span><br><span class="line">			<span class="keyword">if</span> (rs != <span class="literal">null</span>) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					rs.close();</span><br><span class="line">				&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">					e.printStackTrace();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (st != <span class="literal">null</span>) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					st.close();</span><br><span class="line">				&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">					e.printStackTrace();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">if</span> (conn != <span class="literal">null</span>) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					conn.close();</span><br><span class="line">				&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">					e.printStackTrace();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>综上：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566569819744.webp" alt="1566569819744"></p>
<h3 id="3-3-PreparedStatement的使用"><a href="#3-3-PreparedStatement的使用" class="headerlink" title="3.3 PreparedStatement的使用"></a>3.3 PreparedStatement的使用</h3><h4 id="3-3-1-PreparedStatement介绍"><a href="#3-3-1-PreparedStatement介绍" class="headerlink" title="3.3.1 PreparedStatement介绍"></a>3.3.1 PreparedStatement介绍</h4><ul>
<li><p>可以通过调用 Connection 对象的 <strong>preparedStatement(String sql)</strong> 方法获取 PreparedStatement 对象</p>
</li>
<li><p><strong>PreparedStatement 接口是 Statement 的子接口，它表示一条预编译过的 SQL 语句</strong></p>
</li>
<li><p>PreparedStatement 对象所代表的 SQL 语句中的参数用问号(?)来表示，调用 PreparedStatement 对象的 setXxx() 方法来设置这些参数. setXxx() 方法有两个参数，第一个参数是要设置的 SQL 语句中的参数的索引(从 1 开始)，第二个是设置的 SQL 语句中的参数的值</p>
</li>
</ul>
<h4 id="3-3-2-PreparedStatement-vs-Statement"><a href="#3-3-2-PreparedStatement-vs-Statement" class="headerlink" title="3.3.2 PreparedStatement vs Statement"></a>3.3.2 PreparedStatement vs Statement</h4><ul>
<li><p>代码的可读性和可维护性。</p>
</li>
<li><p><strong>PreparedStatement 能最大可能提高性能：</strong></p>
<ul>
<li>DBServer会对<strong>预编译</strong>语句提供性能优化。因为预编译语句有可能被重复调用，所以<u>语句在被DBServer的编译器编译后的执行代码被缓存下来，那么下次调用时只要是相同的预编译语句就不需要编译，只要将参数直接传入编译过的语句执行代码中就会得到执行。</u></li>
<li>在statement语句中,即使是相同操作但因为数据内容不一样,所以整个语句本身不能匹配,没有缓存语句的意义.事实是没有数据库会对普通语句编译后的执行代码缓存。这样<u>每执行一次都要对传入的语句编译一次。</u></li>
<li>(语法检查，语义检查，翻译成二进制命令，缓存)</li>
</ul>
</li>
<li><p>PreparedStatement 可以防止 SQL 注入 </p>
</li>
</ul>
<h4 id="3-3-3-Java与SQL对应数据类型转换表"><a href="#3-3-3-Java与SQL对应数据类型转换表" class="headerlink" title="3.3.3 Java与SQL对应数据类型转换表"></a>3.3.3 Java与SQL对应数据类型转换表</h4><div class="table-container">
<table>
<thead>
<tr>
<th>Java类型</th>
<th>SQL类型</th>
</tr>
</thead>
<tbody>
<tr>
<td>boolean</td>
<td>BIT</td>
</tr>
<tr>
<td>byte</td>
<td>TINYINT</td>
</tr>
<tr>
<td>short</td>
<td>SMALLINT</td>
</tr>
<tr>
<td>int</td>
<td>INTEGER</td>
</tr>
<tr>
<td>long</td>
<td>BIGINT</td>
</tr>
<tr>
<td>String</td>
<td>CHAR,VARCHAR,LONGVARCHAR</td>
</tr>
<tr>
<td>byte   array</td>
<td>BINARY  ,    VAR BINARY</td>
</tr>
<tr>
<td>java.sql.Date</td>
<td>DATE</td>
</tr>
<tr>
<td>java.sql.Time</td>
<td>TIME</td>
</tr>
<tr>
<td>java.sql.Timestamp</td>
<td>TIMESTAMP</td>
</tr>
</tbody>
</table>
</div>
<h4 id="3-3-4-使用PreparedStatement实现增、删、改操作"><a href="#3-3-4-使用PreparedStatement实现增、删、改操作" class="headerlink" title="3.3.4 使用PreparedStatement实现增、删、改操作"></a>3.3.4 使用PreparedStatement实现增、删、改操作</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//通用的增、删、改操作（体现一：增、删、改 ； 体现二：针对于不同的表）</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(String sql,Object ... args)</span>&#123;</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">//1.获取数据库的连接</span></span><br><span class="line">		conn = JDBCUtils.getConnection();</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//2.获取PreparedStatement的实例 (或：预编译sql语句)</span></span><br><span class="line">		ps = conn.prepareStatement(sql);</span><br><span class="line">		<span class="comment">//3.填充占位符</span></span><br><span class="line">		<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>;i &lt; args.length;i++)&#123;</span><br><span class="line">			ps.setObject(i + <span class="number">1</span>, args[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//4.执行sql语句</span></span><br><span class="line">		ps.execute();</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">		<span class="comment">//5.关闭资源</span></span><br><span class="line">		JDBCUtils.closeResource(conn, ps);</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="3-3-5-使用PreparedStatement实现查询操作"><a href="#3-3-5-使用PreparedStatement实现查询操作" class="headerlink" title="3.3.5 使用PreparedStatement实现查询操作"></a>3.3.5 使用PreparedStatement实现查询操作</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 通用的针对于不同表的查询:返回一个对象 (version 1.0)</span></span><br><span class="line"><span class="keyword">public</span> &lt;T&gt; T <span class="title function_">getInstance</span><span class="params">(Class&lt;T&gt; clazz, String sql, Object... args)</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="type">ResultSet</span> <span class="variable">rs</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// 1.获取数据库连接</span></span><br><span class="line">		conn = JDBCUtils.getConnection();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 2.预编译sql语句，得到PreparedStatement对象</span></span><br><span class="line">		ps = conn.prepareStatement(sql);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 3.填充占位符</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; args.length; i++) &#123;</span><br><span class="line">			ps.setObject(i + <span class="number">1</span>, args[i]);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 4.执行executeQuery(),得到结果集：ResultSet</span></span><br><span class="line">		rs = ps.executeQuery();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 5.得到结果集的元数据：ResultSetMetaData</span></span><br><span class="line">		<span class="type">ResultSetMetaData</span> <span class="variable">rsmd</span> <span class="operator">=</span> rs.getMetaData();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 6.1通过ResultSetMetaData得到columnCount,columnLabel；通过ResultSet得到列值</span></span><br><span class="line">		<span class="type">int</span> <span class="variable">columnCount</span> <span class="operator">=</span> rsmd.getColumnCount();</span><br><span class="line">		<span class="keyword">if</span> (rs.next()) &#123;</span><br><span class="line">			<span class="type">T</span> <span class="variable">t</span> <span class="operator">=</span> clazz.newInstance();</span><br><span class="line">			<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; columnCount; i++) &#123;<span class="comment">// 遍历每一个列</span></span><br><span class="line"></span><br><span class="line">				<span class="comment">// 获取列值</span></span><br><span class="line">				<span class="type">Object</span> <span class="variable">columnVal</span> <span class="operator">=</span> rs.getObject(i + <span class="number">1</span>);</span><br><span class="line">				<span class="comment">// 获取列的别名:列的别名，使用类的属性名充当</span></span><br><span class="line">				<span class="type">String</span> <span class="variable">columnLabel</span> <span class="operator">=</span> rsmd.getColumnLabel(i + <span class="number">1</span>);</span><br><span class="line">				<span class="comment">// 6.2使用反射，给对象的相应属性赋值</span></span><br><span class="line">				<span class="type">Field</span> <span class="variable">field</span> <span class="operator">=</span> clazz.getDeclaredField(columnLabel);</span><br><span class="line">				field.setAccessible(<span class="literal">true</span>);</span><br><span class="line">				field.set(t, columnVal);</span><br><span class="line"></span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">return</span> t;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line"></span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="comment">// 7.关闭资源</span></span><br><span class="line">		JDBCUtils.closeResource(conn, ps, rs);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>说明：使用PreparedStatement实现的查询操作可以替换Statement实现的查询操作，解决Statement拼串和SQL注入问题。</p>
</blockquote>
<h3 id="3-4-ResultSet与ResultSetMetaData"><a href="#3-4-ResultSet与ResultSetMetaData" class="headerlink" title="3.4 ResultSet与ResultSetMetaData"></a>3.4 ResultSet与ResultSetMetaData</h3><h4 id="3-4-1-ResultSet"><a href="#3-4-1-ResultSet" class="headerlink" title="3.4.1 ResultSet"></a>3.4.1 ResultSet</h4><ul>
<li><p>查询需要调用PreparedStatement 的 executeQuery() 方法，查询结果是一个ResultSet 对象</p>
</li>
<li><p>ResultSet 对象以逻辑表格的形式封装了执行数据库操作的结果集，ResultSet 接口由数据库厂商提供实现</p>
</li>
<li><p>ResultSet 返回的实际上就是一张数据表。有一个指针指向数据表的第一条记录的前面。</p>
</li>
<li><p>ResultSet 对象维护了一个指向当前数据行的<strong>游标</strong>，初始的时候，游标在第一行之前，可以通过 ResultSet 对象的 next() 方法移动到下一行。调用 next()方法检测下一行是否有效。若有效，该方法返回 true，且指针下移。相当于Iterator对象的 hasNext() 和 next() 方法的结合体。</p>
</li>
<li><p>当指针指向一行时, 可以通过调用 getXxx(int index) 或 getXxx(int columnName) 获取每一列的值。</p>
<ul>
<li>例如: getInt(1), getString(“name”)</li>
<li><strong>注意：Java与数据库交互涉及到的相关Java API中的索引都从1开始。</strong></li>
</ul>
</li>
<li><p>ResultSet 接口的常用方法：</p>
<ul>
<li><p>boolean next()</p>
</li>
<li><p>getString()</p>
</li>
<li>…</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555580152530.webp" alt="1555580152530"></p>
</li>
</ul>
<h4 id="3-4-2-ResultSetMetaData"><a href="#3-4-2-ResultSetMetaData" class="headerlink" title="3.4.2 ResultSetMetaData"></a>3.4.2 ResultSetMetaData</h4><ul>
<li><p>可用于获取关于 ResultSet 对象中列的类型和属性信息的对象</p>
</li>
<li><p>ResultSetMetaData meta = rs.getMetaData();</p>
<ul>
<li><strong>getColumnName</strong>(int column)：获取指定列的名称</li>
<li><strong>getColumnLabel</strong>(int column)：获取指定列的别名</li>
<li><p><strong>getColumnCount</strong>()：返回当前 ResultSet 对象中的列数。 </p>
</li>
<li><p>getColumnTypeName(int column)：检索指定列的数据库特定的类型名称。 </p>
</li>
<li>getColumnDisplaySize(int column)：指示指定列的最大标准宽度，以字符为单位。 </li>
<li><p><strong>isNullable</strong>(int column)：指示指定列中的值是否可以为 null。 </p>
</li>
<li><p>isAutoIncrement(int column)：指示是否自动为指定列进行编号，这样这些列仍然是只读的。 </p>
</li>
</ul>
</li>
</ul>
<p><strong>问题1：得到结果集后, 如何知道该结果集中有哪些列 ？ 列名是什么？</strong></p>
<pre><code> 需要使用一个描述 ResultSet 的对象， 即 ResultSetMetaData
</code></pre><p><strong>问题2：关于ResultSetMetaData</strong></p>
<ol>
<li><strong>如何获取 ResultSetMetaData</strong>： 调用 ResultSet 的 getMetaData() 方法即可</li>
<li><strong>获取 ResultSet 中有多少列</strong>：调用 ResultSetMetaData 的 getColumnCount() 方法</li>
<li><strong>获取 ResultSet 每一列的列的别名是什么</strong>：调用 ResultSetMetaData 的getColumnLabel() 方法</li>
</ol>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555579816884.webp" alt="1555579816884"></p>
<h3 id="3-5-资源的释放"><a href="#3-5-资源的释放" class="headerlink" title="3.5 资源的释放"></a>3.5 资源的释放</h3><ul>
<li>释放ResultSet, Statement,Connection。</li>
<li>数据库连接（Connection）是非常稀有的资源，用完后必须马上释放，如果Connection不能及时正确的关闭将导致系统宕机。Connection的使用原则是<strong>尽量晚创建，尽量早的释放。</strong></li>
<li>可以在finally中关闭，保证及时其他代码出现异常，资源也一定能被关闭。</li>
</ul>
<h3 id="3-6-JDBC-API小结"><a href="#3-6-JDBC-API小结" class="headerlink" title="3.6 JDBC API小结"></a>3.6 JDBC API小结</h3><ul>
<li><p>两种思想</p>
<ul>
<li><p>面向接口编程的思想</p>
</li>
<li><p>ORM思想(object relational mapping)</p>
<ul>
<li>一个数据表对应一个java类</li>
<li>表中的一条记录对应java类的一个对象</li>
<li>表中的一个字段对应java类的一个属性</li>
</ul>
</li>
</ul>
<blockquote>
<p>sql是需要结合列名和表的属性名来写。注意起别名。</p>
</blockquote>
</li>
<li><p>两种技术</p>
<ul>
<li>JDBC结果集的元数据：ResultSetMetaData<ul>
<li>获取列数：getColumnCount()</li>
<li>获取列的别名：getColumnLabel()</li>
</ul>
</li>
<li>通过反射，创建指定类的对象，获取指定的属性并赋值</li>
</ul>
</li>
</ul>
<hr>
<h2 id="章节练习"><a href="#章节练习" class="headerlink" title="章节练习"></a>章节练习</h2><p><strong>练习题1：从控制台向数据库的表customers中插入一条数据，表结构如下：</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555580275036.webp" alt="1555580275036"></p>
<p><strong>练习题2：创立数据库表 examstudent，表结构如下：</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555580735377.webp" alt="1555580735377"></p>
<p>向数据表中添加如下数据：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555580763636.webp" alt="1555580763636"></p>
<p><strong>代码实现1：插入一个新的student 信息</strong></p>
<p>请输入考生的详细信息</p>
<p>Type:<br>IDCard:<br>ExamCard:<br>StudentName:<br>Location:<br>Grade:</p>
<p>信息录入成功!</p>
<p><strong>代码实现2：在 eclipse中建立 java 程序：输入身份证号或准考证号可以查询到学生的基本信息。结果如下：</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555580937490.webp" alt="1555580937490"></p>
<p><strong>代码实现3：完成学生信息的删除功能</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555580965019.webp" alt="1555580965019"></p>
<hr>
<h2 id="第4章-操作BLOB类型字段"><a href="#第4章-操作BLOB类型字段" class="headerlink" title="第4章 操作BLOB类型字段"></a>第4章 操作BLOB类型字段</h2><h3 id="4-1-MySQL-BLOB类型"><a href="#4-1-MySQL-BLOB类型" class="headerlink" title="4.1 MySQL BLOB类型"></a>4.1 MySQL BLOB类型</h3><ul>
<li>MySQL中，BLOB是一个二进制大型对象，是一个可以存储大量数据的容器，它能容纳不同大小的数据。</li>
<li><p>插入BLOB类型的数据必须使用PreparedStatement，因为BLOB类型的数据无法使用字符串拼接写的。</p>
</li>
<li><p>MySQL的四种BLOB类型(除了在存储的最大信息量上不同外，他们是等同的)</p>
</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555581069798.webp" alt="1555581069798"></p>
<ul>
<li>实际使用中根据需要存入的数据大小定义不同的BLOB类型。</li>
<li>需要注意的是：如果存储的文件过大，数据库的性能会下降。</li>
<li>如果在指定了相关的Blob类型以后，还报错：xxx too large，那么在mysql的安装目录下，找my.ini文件加上如下的配置参数： <strong>max_allowed_packet=16M</strong>。同时注意：修改了my.ini文件之后，需要重新启动mysql服务。</li>
</ul>
<h3 id="4-2-向数据表中插入大数据类型"><a href="#4-2-向数据表中插入大数据类型" class="headerlink" title="4.2 向数据表中插入大数据类型"></a>4.2 向数据表中插入大数据类型</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取连接</span></span><br><span class="line"><span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection();</span><br><span class="line">		</span><br><span class="line"><span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into customers(name,email,birth,photo)values(?,?,?,?)&quot;</span>;</span><br><span class="line"><span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> conn.prepareStatement(sql);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 填充占位符</span></span><br><span class="line">ps.setString(<span class="number">1</span>, <span class="string">&quot;徐海强&quot;</span>);</span><br><span class="line">ps.setString(<span class="number">2</span>, <span class="string">&quot;xhq@126.com&quot;</span>);</span><br><span class="line">ps.setDate(<span class="number">3</span>, <span class="keyword">new</span> <span class="title class_">Date</span>(<span class="keyword">new</span> <span class="title class_">java</span>.util.Date().getTime()));</span><br><span class="line"><span class="comment">// 操作Blob类型的变量</span></span><br><span class="line"><span class="type">FileInputStream</span> <span class="variable">fis</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;xhq.webp&quot;</span>);</span><br><span class="line">ps.setBlob(<span class="number">4</span>, fis);</span><br><span class="line"><span class="comment">//执行</span></span><br><span class="line">ps.execute();</span><br><span class="line">		</span><br><span class="line">fis.close();</span><br><span class="line">JDBCUtils.closeResource(conn, ps);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="4-3-修改数据表中的Blob类型字段"><a href="#4-3-修改数据表中的Blob类型字段" class="headerlink" title="4.3 修改数据表中的Blob类型字段"></a>4.3 修改数据表中的Blob类型字段</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection();</span><br><span class="line"><span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;update customers set photo = ? where id = ?&quot;</span>;</span><br><span class="line"><span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> conn.prepareStatement(sql);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 填充占位符</span></span><br><span class="line"><span class="comment">// 操作Blob类型的变量</span></span><br><span class="line"><span class="type">FileInputStream</span> <span class="variable">fis</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;coffee.webp&quot;</span>);</span><br><span class="line">ps.setBlob(<span class="number">1</span>, fis);</span><br><span class="line">ps.setInt(<span class="number">2</span>, <span class="number">25</span>);</span><br><span class="line"></span><br><span class="line">ps.execute();</span><br><span class="line"></span><br><span class="line">fis.close();</span><br><span class="line">JDBCUtils.closeResource(conn, ps);</span><br></pre></td></tr></table></figure>
<h3 id="4-4-从数据表中读取大数据类型"><a href="#4-4-从数据表中读取大数据类型" class="headerlink" title="4.4 从数据表中读取大数据类型"></a>4.4 从数据表中读取大数据类型</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;SELECT id, name, email, birth, photo FROM customer WHERE id = ?&quot;</span>;</span><br><span class="line">conn = getConnection();</span><br><span class="line">ps = conn.prepareStatement(sql);</span><br><span class="line">ps.setInt(<span class="number">1</span>, <span class="number">8</span>);</span><br><span class="line">rs = ps.executeQuery();</span><br><span class="line"><span class="keyword">if</span>(rs.next())&#123;</span><br><span class="line">	<span class="type">Integer</span> <span class="variable">id</span> <span class="operator">=</span> rs.getInt(<span class="number">1</span>);</span><br><span class="line">    <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> rs.getString(<span class="number">2</span>);</span><br><span class="line">	<span class="type">String</span> <span class="variable">email</span> <span class="operator">=</span> rs.getString(<span class="number">3</span>);</span><br><span class="line">    <span class="type">Date</span> <span class="variable">birth</span> <span class="operator">=</span> rs.getDate(<span class="number">4</span>);</span><br><span class="line">	<span class="type">Customer</span> <span class="variable">cust</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Customer</span>(id, name, email, birth);</span><br><span class="line">    System.out.println(cust); </span><br><span class="line">    <span class="comment">//读取Blob类型的字段</span></span><br><span class="line">	<span class="type">Blob</span> <span class="variable">photo</span> <span class="operator">=</span> rs.getBlob(<span class="number">5</span>);</span><br><span class="line">	<span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> photo.getBinaryStream();</span><br><span class="line">	<span class="type">OutputStream</span> <span class="variable">os</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;c.webp&quot;</span>);</span><br><span class="line">	<span class="type">byte</span> [] buffer = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>];</span><br><span class="line">	<span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">while</span>((len = is.read(buffer)) != -<span class="number">1</span>)&#123;</span><br><span class="line">		os.write(buffer, <span class="number">0</span>, len);</span><br><span class="line">	&#125;</span><br><span class="line">    JDBCUtils.closeResource(conn, ps, rs);</span><br><span class="line">		</span><br><span class="line">	<span class="keyword">if</span>(is != <span class="literal">null</span>)&#123;</span><br><span class="line">		is.close();</span><br><span class="line">	&#125;</span><br><span class="line">		</span><br><span class="line">	<span class="keyword">if</span>(os !=  <span class="literal">null</span>)&#123;</span><br><span class="line">		os.close();</span><br><span class="line">	&#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="第5章-批量插入"><a href="#第5章-批量插入" class="headerlink" title="第5章 批量插入"></a>第5章 批量插入</h2><h3 id="5-1-批量执行SQL语句"><a href="#5-1-批量执行SQL语句" class="headerlink" title="5.1 批量执行SQL语句"></a>5.1 批量执行SQL语句</h3><p>当需要成批插入或者更新记录时，可以采用Java的批量<strong>更新</strong>机制，这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率</p>
<p>JDBC的批量处理语句包括下面三个方法：</p>
<ul>
<li><strong>addBatch(String)：添加需要批量处理的SQL语句或是参数；</strong></li>
<li><strong>executeBatch()：执行批量处理语句；</strong></li>
<li><strong>clearBatch():清空缓存的数据</strong></li>
</ul>
<p>通常我们会遇到两种批量执行SQL语句的情况：</p>
<ul>
<li>多条SQL语句的批量处理；</li>
<li>一个SQL语句的批量传参；</li>
</ul>
<h3 id="5-2-高效的批量插入"><a href="#5-2-高效的批量插入" class="headerlink" title="5.2 高效的批量插入"></a>5.2 高效的批量插入</h3><p>举例：向数据表中插入20000条数据</p>
<ul>
<li>数据库中提供一个goods表。创建如下：</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> goods(</span><br><span class="line">id <span class="type">INT</span> <span class="keyword">PRIMARY</span> KEY AUTO_INCREMENT,</span><br><span class="line">NAME <span class="type">VARCHAR</span>(<span class="number">20</span>)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h4 id="5-2-1-实现层次一：使用Statement"><a href="#5-2-1-实现层次一：使用Statement" class="headerlink" title="5.2.1 实现层次一：使用Statement"></a>5.2.1 实现层次一：使用Statement</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection();</span><br><span class="line"><span class="type">Statement</span> <span class="variable">st</span> <span class="operator">=</span> conn.createStatement();</span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>;i &lt;= <span class="number">20000</span>;i++)&#123;</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into goods(name) values(&#x27;name_&#x27; + &quot;</span>+ i +<span class="string">&quot;)&quot;</span>;</span><br><span class="line">	st.executeUpdate(sql);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-2-2-实现层次二：使用PreparedStatement"><a href="#5-2-2-实现层次二：使用PreparedStatement" class="headerlink" title="5.2.2 实现层次二：使用PreparedStatement"></a>5.2.2 实现层次二：使用PreparedStatement</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">long</span> <span class="variable">start</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">		</span><br><span class="line"><span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection();</span><br><span class="line">		</span><br><span class="line"><span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into goods(name)values(?)&quot;</span>;</span><br><span class="line"><span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> conn.prepareStatement(sql);</span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>;i &lt;= <span class="number">20000</span>;i++)&#123;</span><br><span class="line">	ps.setString(<span class="number">1</span>, <span class="string">&quot;name_&quot;</span> + i);</span><br><span class="line">	ps.executeUpdate();</span><br><span class="line">&#125;</span><br><span class="line">		</span><br><span class="line"><span class="type">long</span> <span class="variable">end</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">System.out.println(<span class="string">&quot;花费的时间为：&quot;</span> + (end - start));<span class="comment">//82340</span></span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">JDBCUtils.closeResource(conn, ps);</span><br></pre></td></tr></table></figure>
<h4 id="5-2-3-实现层次三"><a href="#5-2-3-实现层次三" class="headerlink" title="5.2.3 实现层次三"></a>5.2.3 实现层次三</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 修改1： 使用 addBatch() / executeBatch() / clearBatch()</span></span><br><span class="line"><span class="comment"> * 修改2：mysql服务器默认是关闭批处理的，我们需要通过一个参数，让mysql开启批处理的支持。</span></span><br><span class="line"><span class="comment"> * 		 ?rewriteBatchedStatements=true 写在配置文件的url后面</span></span><br><span class="line"><span class="comment"> * 修改3：使用更新的mysql 驱动：mysql-connector-java-5.1.37-bin.jar</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsert1</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">long</span> <span class="variable">start</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">		</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection();</span><br><span class="line">		</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into goods(name)values(?)&quot;</span>;</span><br><span class="line">	<span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> conn.prepareStatement(sql);</span><br><span class="line">		</span><br><span class="line">	<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>;i &lt;= <span class="number">1000000</span>;i++)&#123;</span><br><span class="line">		ps.setString(<span class="number">1</span>, <span class="string">&quot;name_&quot;</span> + i);</span><br><span class="line">			</span><br><span class="line">		<span class="comment">//1.“攒”sql</span></span><br><span class="line">		ps.addBatch();</span><br><span class="line">		<span class="keyword">if</span>(i % <span class="number">500</span> == <span class="number">0</span>)&#123;</span><br><span class="line">			<span class="comment">//2.执行</span></span><br><span class="line">			ps.executeBatch();</span><br><span class="line">			<span class="comment">//3.清空</span></span><br><span class="line">			ps.clearBatch();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">		</span><br><span class="line">	<span class="type">long</span> <span class="variable">end</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">	System.out.println(<span class="string">&quot;花费的时间为：&quot;</span> + (end - start));<span class="comment">//20000条：625                                                                         //1000000条:14733  </span></span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, ps);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-2-4-实现层次四"><a href="#5-2-4-实现层次四" class="headerlink" title="5.2.4 实现层次四"></a>5.2.4 实现层次四</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 层次四：在层次三的基础上操作</span></span><br><span class="line"><span class="comment">* 使用Connection 的 setAutoCommit(false)  /  commit()</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsert2</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">long</span> <span class="variable">start</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">		</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection();</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//1.设置为不自动提交数据</span></span><br><span class="line">	conn.setAutoCommit(<span class="literal">false</span>);</span><br><span class="line">		</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into goods(name)values(?)&quot;</span>;</span><br><span class="line">	<span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> conn.prepareStatement(sql);</span><br><span class="line">		</span><br><span class="line">	<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>;i &lt;= <span class="number">1000000</span>;i++)&#123;</span><br><span class="line">		ps.setString(<span class="number">1</span>, <span class="string">&quot;name_&quot;</span> + i);</span><br><span class="line">			</span><br><span class="line">		<span class="comment">//1.“攒”sql</span></span><br><span class="line">		ps.addBatch();</span><br><span class="line">			</span><br><span class="line">		<span class="keyword">if</span>(i % <span class="number">500</span> == <span class="number">0</span>)&#123;</span><br><span class="line">			<span class="comment">//2.执行</span></span><br><span class="line">			ps.executeBatch();</span><br><span class="line">			<span class="comment">//3.清空</span></span><br><span class="line">			ps.clearBatch();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//2.提交数据</span></span><br><span class="line">	conn.commit();</span><br><span class="line">		</span><br><span class="line">	<span class="type">long</span> <span class="variable">end</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line">	System.out.println(<span class="string">&quot;花费的时间为：&quot;</span> + (end - start));<span class="comment">//1000000条:4978 </span></span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, ps);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="第6章：-数据库事务"><a href="#第6章：-数据库事务" class="headerlink" title="第6章： 数据库事务"></a>第6章： 数据库事务</h2><h3 id="6-1-数据库事务介绍"><a href="#6-1-数据库事务介绍" class="headerlink" title="6.1 数据库事务介绍"></a>6.1 数据库事务介绍</h3><ul>
<li><p><strong>事务：一组逻辑操作单元,使数据从一种状态变换到另一种状态。</strong></p>
</li>
<li><p><strong>事务处理（事务操作）：</strong>保证所有事务都作为一个工作单元来执行，即使出现了故障，都不能改变这种执行方式。当在一个事务中执行多个操作时，要么所有的事务都<strong>被提交(commit)</strong>，那么这些修改就永久地保存下来；要么数据库管理系统将放弃所作的所有修改，整个事务<strong>回滚(rollback)</strong>到最初状态。</p>
</li>
<li><p>为确保数据库中数据的<strong>一致性</strong>，数据的操纵应当是离散的成组的逻辑单元：当它全部完成时，数据的一致性可以保持，而当这个单元中的一部分操作失败，整个事务应全部视为错误，所有从起始点以后的操作应全部回退到开始状态。 </p>
</li>
</ul>
<h3 id="6-2-JDBC事务处理"><a href="#6-2-JDBC事务处理" class="headerlink" title="6.2 JDBC事务处理"></a>6.2 JDBC事务处理</h3><ul>
<li>数据一旦提交，就不可回滚。</li>
<li>数据什么时候意味着提交？<ul>
<li><strong>当一个连接对象被创建时，默认情况下是自动提交事务</strong>：每次执行一个 SQL 语句时，如果执行成功，就会向数据库自动提交，而不能回滚。</li>
<li><strong>关闭数据库连接，数据就会自动的提交。</strong>如果多个操作，每个操作使用的是自己单独的连接，则无法保证事务。即同一个事务的多个操作必须在同一个连接下。</li>
</ul>
</li>
<li><p><strong>JDBC程序中为了让多个 SQL 语句作为一个事务执行：</strong></p>
<ul>
<li>调用 Connection 对象的 <strong>setAutoCommit(false);</strong> 以取消自动提交事务</li>
<li>在所有的 SQL 语句都成功执行后，调用 <strong>commit();</strong> 方法提交事务</li>
<li>在出现异常时，调用 <strong>rollback();</strong> 方法回滚事务</li>
</ul>
<blockquote>
<p>若此时 Connection 没有被关闭，还可能被重复使用，则需要恢复其自动提交状态 setAutoCommit(true)。尤其是在使用数据库连接池技术时，执行close()方法前，建议恢复自动提交状态。</p>
</blockquote>
</li>
</ul>
<p>【案例：用户AA向用户BB转账100】</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testJDBCTransaction</span><span class="params">()</span> &#123;</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// 1.获取数据库连接</span></span><br><span class="line">		conn = JDBCUtils.getConnection();</span><br><span class="line">		<span class="comment">// 2.开启事务</span></span><br><span class="line">		conn.setAutoCommit(<span class="literal">false</span>);</span><br><span class="line">		<span class="comment">// 3.进行数据库操作</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql1</span> <span class="operator">=</span> <span class="string">&quot;update user_table set balance = balance - 100 where user = ?&quot;</span>;</span><br><span class="line">		update(conn, sql1, <span class="string">&quot;AA&quot;</span>);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 模拟网络异常</span></span><br><span class="line">		<span class="comment">//System.out.println(10 / 0);</span></span><br><span class="line"></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql2</span> <span class="operator">=</span> <span class="string">&quot;update user_table set balance = balance + 100 where user = ?&quot;</span>;</span><br><span class="line">		update(conn, sql2, <span class="string">&quot;BB&quot;</span>);</span><br><span class="line">		<span class="comment">// 4.若没有异常，则提交事务</span></span><br><span class="line">		conn.commit();</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">		<span class="comment">// 5.若有异常，则回滚事务</span></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			conn.rollback();</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e1) &#123;</span><br><span class="line">			e1.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">//6.恢复每次DML操作的自动提交功能</span></span><br><span class="line">			conn.setAutoCommit(<span class="literal">true</span>);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">        <span class="comment">//7.关闭连接</span></span><br><span class="line">		JDBCUtils.closeResource(conn, <span class="literal">null</span>, <span class="literal">null</span>); </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>其中，对数据库操作的方法为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用事务以后的通用的增删改操作（version 2.0）</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(Connection conn ,String sql, Object... args)</span> &#123;</span><br><span class="line">	<span class="type">PreparedStatement</span> <span class="variable">ps</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// 1.获取PreparedStatement的实例 (或：预编译sql语句)</span></span><br><span class="line">		ps = conn.prepareStatement(sql);</span><br><span class="line">		<span class="comment">// 2.填充占位符</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; args.length; i++) &#123;</span><br><span class="line">			ps.setObject(i + <span class="number">1</span>, args[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 3.执行sql语句</span></span><br><span class="line">		ps.execute();</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="comment">// 4.关闭资源</span></span><br><span class="line">		JDBCUtils.closeResource(<span class="literal">null</span>, ps);</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6-3-事务的ACID属性"><a href="#6-3-事务的ACID属性" class="headerlink" title="6.3 事务的ACID属性"></a>6.3 事务的ACID属性</h3><ol>
<li><p><strong>原子性（Atomicity）</strong><br> 原子性是指事务是一个不可分割的工作单位，事务中的操作要么都发生，要么都不发生。 </p>
</li>
<li><p><strong>一致性（Consistency）</strong><br> 事务必须使数据库从一个一致性状态变换到另外一个一致性状态。</p>
</li>
<li><p><strong>隔离性（Isolation）</strong><br> 事务的隔离性是指一个事务的执行不能被其他事务干扰，即一个事务内部的操作及使用的数据对并发的其他事务是隔离的，并发执行的各个事务之间不能互相干扰。</p>
</li>
<li><p><strong>持久性（Durability）</strong><br> 持久性是指一个事务一旦被提交，它对数据库中数据的改变就是永久性的，接下来的其他操作和数据库故障不应该对其有任何影响。</p>
</li>
</ol>
<h4 id="6-3-1-数据库的并发问题"><a href="#6-3-1-数据库的并发问题" class="headerlink" title="6.3.1 数据库的并发问题"></a>6.3.1 数据库的并发问题</h4><ul>
<li><p>对于同时运行的多个事务, 当这些事务访问数据库中相同的数据时, 如果没有采取必要的隔离机制, 就会导致各种并发问题:</p>
<ul>
<li><strong>脏读</strong>: 对于两个事务 T1, T2, T1 读取了已经被 T2 更新但还<strong>没有被提交</strong>的字段。之后, 若 T2 回滚, T1读取的内容就是临时且无效的。</li>
<li><strong>不可重复读</strong>: 对于两个事务T1, T2, T1 读取了一个字段, 然后 T2 <strong>更新</strong>了该字段。之后, T1再次读取同一个字段, 值就不同了。</li>
<li><strong>幻读</strong>: 对于两个事务T1, T2, T1 从一个表中读取了一个字段, 然后 T2 在该表中<strong>插入</strong>了一些新的行。之后, 如果 T1 再次读取同一个表, 就会多出几行。</li>
</ul>
</li>
<li><p><strong>数据库事务的隔离性</strong>: 数据库系统必须具有隔离并发运行各个事务的能力, 使它们不会相互影响, 避免各种并发问题。</p>
</li>
<li><p>一个事务与其他事务隔离的程度称为隔离级别。数据库规定了多种事务隔离级别, 不同隔离级别对应不同的干扰程度, <strong>隔离级别越高, 数据一致性就越好, 但并发性越弱。</strong></p>
</li>
</ul>
<h4 id="6-3-2-四种隔离级别"><a href="#6-3-2-四种隔离级别" class="headerlink" title="6.3.2 四种隔离级别"></a>6.3.2 四种隔离级别</h4><ul>
<li><p>数据库提供的4种事务隔离级别：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555586275271.webp" alt="1555586275271"></p>
</li>
<li><p>Oracle 支持的 2 种事务隔离级别：<strong>READ COMMITED</strong>, SERIALIZABLE。 Oracle 默认的事务隔离级别为: <strong>READ COMMITED</strong> 。</p>
</li>
</ul>
<ul>
<li>Mysql 支持 4 种事务隔离级别。Mysql 默认的事务隔离级别为: <strong>REPEATABLE READ。</strong></li>
</ul>
<h4 id="6-3-3-在MySql中设置隔离级别"><a href="#6-3-3-在MySql中设置隔离级别" class="headerlink" title="6.3.3 在MySql中设置隔离级别"></a>6.3.3 在MySql中设置隔离级别</h4><ul>
<li><p>每启动一个 mysql 程序, 就会获得一个单独的数据库连接. 每个数据库连接都有一个全局变量 @@tx_isolation, 表示当前的事务隔离级别。</p>
</li>
<li><p>查看当前的隔离级别: </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT @@tx_isolation;</span><br></pre></td></tr></table></figure>
</li>
<li><p>设置当前 mySQL 连接的隔离级别:  </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">set  transaction isolation level read committed;</span><br></pre></td></tr></table></figure>
</li>
<li><p>设置数据库系统的全局的隔离级别:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">set global transaction isolation level read committed;</span><br></pre></td></tr></table></figure>
</li>
<li><p>补充操作：</p>
<ul>
<li><p>创建mysql数据库用户：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">create user tom identified by &#x27;abc123&#x27;;</span><br></pre></td></tr></table></figure>
</li>
<li><p>授予权限</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">#授予通过网络方式登录的tom用户，对所有库所有表的全部权限，密码设为abc123.</span><br><span class="line">grant all privileges on *.* to tom@&#x27;%&#x27;  identified by &#x27;abc123&#x27;; </span><br><span class="line"></span><br><span class="line"> #给tom用户使用本地命令行方式，授予atguigudb这个库下的所有表的插删改查的权限。</span><br><span class="line">grant select,insert,delete,update on atguigudb.* to tom@localhost identified by &#x27;abc123&#x27;; </span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h2 id="第7章：DAO及相关实现类"><a href="#第7章：DAO及相关实现类" class="headerlink" title="第7章：DAO及相关实现类"></a>第7章：DAO及相关实现类</h2><ul>
<li>DAO：Data Access Object访问数据信息的类和接口，包括了对数据的CRUD（Create、Retrival、Update、Delete），而不包含任何业务相关的信息。有时也称作：BaseDAO</li>
<li>作用：为了实现功能的模块化，更有利于代码的维护和升级。</li>
<li>下面是尚硅谷JavaWeb阶段书城项目中DAO使用的体现：</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566726681515.webp" alt="1566726681515"></p>
<ul>
<li>层次结构：</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1566745811244.webp" alt="1566745811244"></p>
<h3 id="【BaseDAO-java】"><a href="#【BaseDAO-java】" class="headerlink" title="【BaseDAO.java】"></a>【BaseDAO.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.ParameterizedType;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Type;</span><br><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"><span class="keyword">import</span> java.sql.SQLException;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.apache.commons.dbutils.QueryRunner;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.dbutils.handlers.BeanHandler;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.dbutils.handlers.BeanListHandler;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.dbutils.handlers.ScalarHandler;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 定义一个用来被继承的对数据库进行基本操作的Dao</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> HanYanBing</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">BaseDao</span>&lt;T&gt; &#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="type">QueryRunner</span> <span class="variable">queryRunner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line">	<span class="comment">// 定义一个变量来接收泛型的类型</span></span><br><span class="line">	<span class="keyword">private</span> Class&lt;T&gt; type;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 获取T的Class对象，获取泛型的类型，泛型是在被子类继承时才确定</span></span><br><span class="line">	<span class="keyword">public</span> <span class="title function_">BaseDao</span><span class="params">()</span> &#123;</span><br><span class="line">		<span class="comment">// 获取子类的类型</span></span><br><span class="line">		<span class="type">Class</span> <span class="variable">clazz</span> <span class="operator">=</span> <span class="built_in">this</span>.getClass();</span><br><span class="line">		<span class="comment">// 获取父类的类型</span></span><br><span class="line">		<span class="comment">// getGenericSuperclass()用来获取当前类的父类的类型</span></span><br><span class="line">		<span class="comment">// ParameterizedType表示的是带泛型的类型</span></span><br><span class="line">		<span class="type">ParameterizedType</span> <span class="variable">parameterizedType</span> <span class="operator">=</span> (ParameterizedType) clazz.getGenericSuperclass();</span><br><span class="line">		<span class="comment">// 获取具体的泛型类型 getActualTypeArguments获取具体的泛型的类型</span></span><br><span class="line">		<span class="comment">// 这个方法会返回一个Type的数组</span></span><br><span class="line">		Type[] types = parameterizedType.getActualTypeArguments();</span><br><span class="line">		<span class="comment">// 获取具体的泛型的类型·</span></span><br><span class="line">		<span class="built_in">this</span>.type = (Class&lt;T&gt;) types[<span class="number">0</span>];</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 通用的增删改操作</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> sql</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> params</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="type">int</span> <span class="title function_">update</span><span class="params">(Connection conn,String sql, Object... params)</span> &#123;</span><br><span class="line">		<span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			count = queryRunner.update(conn, sql, params);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; </span><br><span class="line">		<span class="keyword">return</span> count;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 获取一个对象</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> sql</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> params</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> T <span class="title function_">getBean</span><span class="params">(Connection conn,String sql, Object... params)</span> &#123;</span><br><span class="line">		<span class="type">T</span> <span class="variable">t</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			t = queryRunner.query(conn, sql, <span class="keyword">new</span> <span class="title class_">BeanHandler</span>&lt;T&gt;(type), params);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; </span><br><span class="line">		<span class="keyword">return</span> t;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 获取所有对象</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> sql</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> params</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> List&lt;T&gt; <span class="title function_">getBeanList</span><span class="params">(Connection conn,String sql, Object... params)</span> &#123;</span><br><span class="line">		List&lt;T&gt; list = <span class="literal">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			list = queryRunner.query(conn, sql, <span class="keyword">new</span> <span class="title class_">BeanListHandler</span>&lt;T&gt;(type), params);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; </span><br><span class="line">		<span class="keyword">return</span> list;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 获取一个但一值得方法，专门用来执行像 select count(*)...这样的sql语句</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> sql</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> params</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> Object <span class="title function_">getValue</span><span class="params">(Connection conn,String sql, Object... params)</span> &#123;</span><br><span class="line">		<span class="type">Object</span> <span class="variable">count</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// 调用queryRunner的query方法获取一个单一的值</span></span><br><span class="line">			count = queryRunner.query(conn, sql, <span class="keyword">new</span> <span class="title class_">ScalarHandler</span>&lt;&gt;(), params);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; </span><br><span class="line">		<span class="keyword">return</span> count;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="【BookDAO-java】"><a href="#【BookDAO-java】" class="headerlink" title="【BookDAO.java】"></a>【BookDAO.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.beans.Book;</span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.beans.Page;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">BookDao</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 从数据库中查询出所有的记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	List&lt;Book&gt; <span class="title function_">getBooks</span><span class="params">(Connection conn)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 向数据库中插入一条记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> book</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">saveBook</span><span class="params">(Connection conn,Book book)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 从数据库中根据图书的id删除一条记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> bookId</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">deleteBookById</span><span class="params">(Connection conn,String bookId)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 根据图书的id从数据库中查询出一条记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> bookId</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	Book <span class="title function_">getBookById</span><span class="params">(Connection conn,String bookId)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 根据图书的id从数据库中更新一条记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> book</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">updateBook</span><span class="params">(Connection conn,Book book)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 获取带分页的图书信息</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> page：是只包含了用户输入的pageNo属性的page对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 返回的Page对象是包含了所有属性的Page对象</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	Page&lt;Book&gt; <span class="title function_">getPageBooks</span><span class="params">(Connection conn,Page&lt;Book&gt; page)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 获取带分页和价格范围的图书信息</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> page：是只包含了用户输入的pageNo属性的page对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 返回的Page对象是包含了所有属性的Page对象</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	Page&lt;Book&gt; <span class="title function_">getPageBooksByPrice</span><span class="params">(Connection conn,Page&lt;Book&gt; page, <span class="type">double</span> minPrice, <span class="type">double</span> maxPrice)</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="【UserDAO-java】"><a href="#【UserDAO-java】" class="headerlink" title="【UserDAO.java】"></a>【UserDAO.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.beans.User;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserDao</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 根据User对象中的用户名和密码从数据库中获取一条记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> User 数据库中有记录 null 数据库中无此记录</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	User <span class="title function_">getUser</span><span class="params">(Connection conn,User user)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 根据User对象中的用户名从数据库中获取一条记录</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> true 数据库中有记录 false 数据库中无此记录</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="type">boolean</span> <span class="title function_">checkUsername</span><span class="params">(Connection conn,User user)</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 向数据库中插入User对象</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">saveUser</span><span class="params">(Connection conn,User user)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="【BookDaoImpl-java】"><a href="#【BookDaoImpl-java】" class="headerlink" title="【BookDaoImpl.java】"></a>【BookDaoImpl.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.dao.impl;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.beans.Book;</span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.beans.Page;</span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.dao.BaseDao;</span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.dao.BookDao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">BookDaoImpl</span> <span class="keyword">extends</span> <span class="title class_">BaseDao</span>&lt;Book&gt; <span class="keyword">implements</span> <span class="title class_">BookDao</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> List&lt;Book&gt; <span class="title function_">getBooks</span><span class="params">(Connection conn)</span> &#123;</span><br><span class="line">		<span class="comment">// 调用BaseDao中得到一个List的方法</span></span><br><span class="line">		List&lt;Book&gt; beanList = <span class="literal">null</span>;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,title,author,price,sales,stock,img_path imgPath from books&quot;</span>;</span><br><span class="line">		beanList = getBeanList(conn,sql);</span><br><span class="line">		<span class="keyword">return</span> beanList;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">saveBook</span><span class="params">(Connection conn,Book book)</span> &#123;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into books(title,author,price,sales,stock,img_path) values(?,?,?,?,?,?)&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中通用的增删改的方法</span></span><br><span class="line">		update(conn,sql, book.getTitle(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(),book.getImgPath());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">deleteBookById</span><span class="params">(Connection conn,String bookId)</span> &#123;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;DELETE FROM books WHERE id = ?&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中通用增删改的方法</span></span><br><span class="line">		update(conn,sql, bookId);</span><br><span class="line">			</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> Book <span class="title function_">getBookById</span><span class="params">(Connection conn,String bookId)</span> &#123;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个对象的方法</span></span><br><span class="line">		<span class="type">Book</span> <span class="variable">book</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,title,author,price,sales,stock,img_path imgPath from books where id = ?&quot;</span>;</span><br><span class="line">		book = getBean(conn,sql, bookId);</span><br><span class="line">		<span class="keyword">return</span> book;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">updateBook</span><span class="params">(Connection conn,Book book)</span> &#123;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;update books set title = ? , author = ? , price = ? , sales = ? , stock = ? where id = ?&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中通用的增删改的方法</span></span><br><span class="line">		update(conn,sql, book.getTitle(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(), book.getId());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> Page&lt;Book&gt; <span class="title function_">getPageBooks</span><span class="params">(Connection conn,Page&lt;Book&gt; page)</span> &#123;</span><br><span class="line">		<span class="comment">// 获取数据库中图书的总记录数</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select count(*) from books&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个单一值的方法</span></span><br><span class="line">		<span class="type">long</span> <span class="variable">totalRecord</span> <span class="operator">=</span> (<span class="type">long</span>) getValue(conn,sql);</span><br><span class="line">		<span class="comment">// 将总记录数设置都page对象中</span></span><br><span class="line">		page.setTotalRecord((<span class="type">int</span>) totalRecord);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 获取当前页中的记录存放的List</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql2</span> <span class="operator">=</span> <span class="string">&quot;select id,title,author,price,sales,stock,img_path imgPath from books limit ?,?&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个集合的方法</span></span><br><span class="line">		List&lt;Book&gt; beanList = getBeanList(conn,sql2, (page.getPageNo() - <span class="number">1</span>) * Page.PAGE_SIZE, Page.PAGE_SIZE);</span><br><span class="line">		<span class="comment">// 将这个List设置到page对象中</span></span><br><span class="line">		page.setList(beanList);</span><br><span class="line">		<span class="keyword">return</span> page;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> Page&lt;Book&gt; <span class="title function_">getPageBooksByPrice</span><span class="params">(Connection conn,Page&lt;Book&gt; page, <span class="type">double</span> minPrice, <span class="type">double</span> maxPrice)</span> &#123;</span><br><span class="line">		<span class="comment">// 获取数据库中图书的总记录数</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select count(*) from books where price between ? and ?&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个单一值的方法</span></span><br><span class="line">		<span class="type">long</span> <span class="variable">totalRecord</span> <span class="operator">=</span> (<span class="type">long</span>) getValue(conn,sql,minPrice,maxPrice);</span><br><span class="line">		<span class="comment">// 将总记录数设置都page对象中</span></span><br><span class="line">		page.setTotalRecord((<span class="type">int</span>) totalRecord);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 获取当前页中的记录存放的List</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql2</span> <span class="operator">=</span> <span class="string">&quot;select id,title,author,price,sales,stock,img_path imgPath from books where price between ? and ? limit ?,?&quot;</span>;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个集合的方法</span></span><br><span class="line">		List&lt;Book&gt; beanList = getBeanList(conn,sql2, minPrice , maxPrice , (page.getPageNo() - <span class="number">1</span>) * Page.PAGE_SIZE, Page.PAGE_SIZE);</span><br><span class="line">		<span class="comment">// 将这个List设置到page对象中</span></span><br><span class="line">		page.setList(beanList);</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">return</span> page;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="【UserDaoImpl-java】"><a href="#【UserDaoImpl-java】" class="headerlink" title="【UserDaoImpl.java】"></a>【UserDaoImpl.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.dao.impl;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.beans.User;</span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.dao.BaseDao;</span><br><span class="line"><span class="keyword">import</span> com.atguigu.bookstore.dao.UserDao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserDaoImpl</span> <span class="keyword">extends</span> <span class="title class_">BaseDao</span>&lt;User&gt; <span class="keyword">implements</span> <span class="title class_">UserDao</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> User <span class="title function_">getUser</span><span class="params">(Connection conn,User user)</span> &#123;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个对象的方法</span></span><br><span class="line">		<span class="type">User</span> <span class="variable">bean</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,username,password,email from users where username = ? and password = ?&quot;</span>;</span><br><span class="line">		bean = getBean(conn,sql, user.getUsername(), user.getPassword());</span><br><span class="line">		<span class="keyword">return</span> bean;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">checkUsername</span><span class="params">(Connection conn,User user)</span> &#123;</span><br><span class="line">		<span class="comment">// 调用BaseDao中获取一个对象的方法</span></span><br><span class="line">		<span class="type">User</span> <span class="variable">bean</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">		<span class="comment">// 写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,username,password,email from users where username = ?&quot;</span>;</span><br><span class="line">		bean = getBean(conn,sql, user.getUsername());</span><br><span class="line">		<span class="keyword">return</span> bean != <span class="literal">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">saveUser</span><span class="params">(Connection conn,User user)</span> &#123;</span><br><span class="line">		<span class="comment">//写sql语句</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into users(username,password,email) values(?,?,?)&quot;</span>;</span><br><span class="line">		<span class="comment">//调用BaseDao中通用的增删改的方法</span></span><br><span class="line">		update(conn,sql, user.getUsername(),user.getPassword(),user.getEmail());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="【Book-java】"><a href="#【Book-java】" class="headerlink" title="【Book.java】"></a>【Book.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.beans;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 图书类</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> songhongkang</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Book</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> Integer id;</span><br><span class="line">	<span class="keyword">private</span> String title; <span class="comment">// 书名</span></span><br><span class="line">	<span class="keyword">private</span> String author; <span class="comment">// 作者</span></span><br><span class="line">	<span class="keyword">private</span> <span class="type">double</span> price; <span class="comment">// 价格</span></span><br><span class="line">	<span class="keyword">private</span> Integer sales; <span class="comment">// 销量</span></span><br><span class="line">	<span class="keyword">private</span> Integer stock; <span class="comment">// 库存</span></span><br><span class="line">	<span class="keyword">private</span> <span class="type">String</span> <span class="variable">imgPath</span> <span class="operator">=</span> <span class="string">&quot;static/img/default.webp&quot;</span>; <span class="comment">// 封面图片的路径</span></span><br><span class="line">	<span class="comment">//构造器，get()，set()，toString()方法略</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="【Page-java】"><a href="#【Page-java】" class="headerlink" title="【Page.java】"></a>【Page.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.beans;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 页码类</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> songhongkang</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Page</span>&lt;T&gt; &#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> List&lt;T&gt; list; <span class="comment">// 每页查到的记录存放的集合</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">PAGE_SIZE</span> <span class="operator">=</span> <span class="number">4</span>; <span class="comment">// 每页显示的记录数</span></span><br><span class="line">	<span class="keyword">private</span> <span class="type">int</span> pageNo; <span class="comment">// 当前页</span></span><br><span class="line"><span class="comment">//	private int totalPageNo; // 总页数，通过计算得到</span></span><br><span class="line">	<span class="keyword">private</span> <span class="type">int</span> totalRecord; <span class="comment">// 总记录数，通过查询数据库得到</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="【User-java】"><a href="#【User-java】" class="headerlink" title="【User.java】"></a>【User.java】</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.bookstore.beans;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 用户类</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> songhongkang</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> Integer id;</span><br><span class="line">	<span class="keyword">private</span> String username;</span><br><span class="line">	<span class="keyword">private</span> String password;</span><br><span class="line">	<span class="keyword">private</span> String email;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="第8章：数据库连接池"><a href="#第8章：数据库连接池" class="headerlink" title="第8章：数据库连接池"></a>第8章：数据库连接池</h2><h3 id="8-1-JDBC数据库连接池的必要性"><a href="#8-1-JDBC数据库连接池的必要性" class="headerlink" title="8.1 JDBC数据库连接池的必要性"></a>8.1 JDBC数据库连接池的必要性</h3><ul>
<li><p>在使用开发基于数据库的web程序时，传统的模式基本是按以下步骤：　　</p>
<ul>
<li><strong>在主程序（如servlet、beans）中建立数据库连接</strong></li>
<li><strong>进行sql操作</strong></li>
<li><strong>断开数据库连接</strong></li>
</ul>
</li>
<li><p>这种模式开发，存在的问题:</p>
<ul>
<li>普通的JDBC数据库连接使用 DriverManager 来获取，每次向数据库建立连接的时候都要将 Connection 加载到内存中，再验证用户名和密码(得花费0.05s～1s的时间)。需要数据库连接的时候，就向数据库要求一个，执行完成后再断开连接。这样的方式将会消耗大量的资源和时间。<strong>数据库的连接资源并没有得到很好的重复利用。</strong>若同时有几百人甚至几千人在线，频繁的进行数据库连接操作将占用很多的系统资源，严重的甚至会造成服务器的崩溃。</li>
<li><strong>对于每一次数据库连接，使用完后都得断开。</strong>否则，如果程序出现异常而未能关闭，将会导致数据库系统中的内存泄漏，最终将导致重启数据库。（回忆：何为Java的内存泄漏？）</li>
<li><strong>这种开发不能控制被创建的连接对象数</strong>，系统资源会被毫无顾及的分配出去，如连接过多，也可能导致内存泄漏，服务器崩溃。 </li>
</ul>
</li>
</ul>
<h3 id="8-2-数据库连接池技术"><a href="#8-2-数据库连接池技术" class="headerlink" title="8.2 数据库连接池技术"></a>8.2 数据库连接池技术</h3><ul>
<li>为解决传统开发中的数据库连接问题，可以采用数据库连接池技术。</li>
<li><p><strong>数据库连接池的基本思想</strong>：就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接，当需要建立数据库连接时，只需从“缓冲池”中取出一个，使用完毕之后再放回去。</p>
</li>
<li><p><strong>数据库连接池</strong>负责分配、管理和释放数据库连接，它<strong>允许应用程序重复使用一个现有的数据库连接，而不是重新建立一个</strong>。</p>
</li>
<li>数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中，这些数据库连接的数量是由<strong>最小数据库连接数来设定</strong>的。无论这些数据库连接是否被使用，连接池都将一直保证至少拥有这么多的连接数量。连接池的<strong>最大数据库连接数量</strong>限定了这个连接池能占有的最大连接数，当应用程序向连接池请求的连接数超过最大连接数量时，这些请求将被加入到等待队列中。</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555593464033.webp" alt="1555593464033"></p>
<ul>
<li><strong>工作原理：</strong></li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/1555593598606.webp" alt="1555593598606"></p>
<ul>
<li><p><strong>数据库连接池技术的优点</strong></p>
<p><strong>1. 资源重用</strong></p>
<p>由于数据库连接得以重用，避免了频繁创建，释放连接引起的大量性能开销。在减少系统消耗的基础上，另一方面也增加了系统运行环境的平稳性。</p>
<p><strong>2. 更快的系统反应速度</strong></p>
<p>数据库连接池在初始化过程中，往往已经创建了若干数据库连接置于连接池中备用。此时连接的初始化工作均已完成。对于业务请求处理而言，直接利用现有可用连接，避免了数据库连接初始化和释放过程的时间开销，从而减少了系统的响应时间</p>
<p><strong>3. 新的资源分配手段</strong></p>
<p>对于多应用共享同一数据库的系统而言，可在应用层通过数据库连接池的配置，实现某一应用最大可用数据库连接数的限制，避免某一应用独占所有的数据库资源</p>
<p><strong>4. 统一的连接管理，避免数据库连接泄漏</strong></p>
<p>在较为完善的数据库连接池实现中，可根据预先的占用超时设定，强制回收被占用连接，从而避免了常规数据库连接操作中可能出现的资源泄露</p>
</li>
</ul>
<h3 id="8-3-多种开源的数据库连接池"><a href="#8-3-多种开源的数据库连接池" class="headerlink" title="8.3 多种开源的数据库连接池"></a>8.3 多种开源的数据库连接池</h3><ul>
<li>JDBC 的数据库连接池使用 javax.sql.DataSource 来表示，DataSource 只是一个接口，该接口通常由服务器(Weblogic, WebSphere, Tomcat)提供实现，也有一些开源组织提供实现：<ul>
<li><strong>DBCP</strong> 是Apache提供的数据库连接池。tomcat 服务器自带dbcp数据库连接池。<strong>速度相对c3p0较快</strong>，但因自身存在BUG，Hibernate3已不再提供支持。</li>
<li><strong>C3P0</strong> 是一个开源组织提供的一个数据库连接池，<strong>速度相对较慢，稳定性还可以。</strong>hibernate官方推荐使用</li>
<li><strong>Proxool</strong> 是sourceforge下的一个开源项目数据库连接池，有监控连接池状态的功能，<strong>稳定性较c3p0差一点</strong></li>
<li><strong>BoneCP</strong> 是一个开源组织提供的数据库连接池，速度快</li>
<li><strong>Druid</strong> 是阿里提供的数据库连接池，据说是集DBCP 、C3P0 、Proxool 优点于一身的数据库连接池，但是速度不确定是否有BoneCP快</li>
</ul>
</li>
<li>DataSource 通常被称为数据源，它包含连接池和连接池管理两个部分，习惯上也经常把 DataSource 称为连接池</li>
<li><strong>DataSource用来取代DriverManager来获取Connection，获取速度快，同时可以大幅度提高数据库访问速度。</strong></li>
<li>特别注意：<ul>
<li>数据源和数据库连接不同，数据源无需创建多个，它是产生数据库连接的工厂，因此<strong>整个应用只需要一个数据源即可。</strong></li>
<li>当数据库访问结束后，程序还是像以前一样关闭数据库连接：conn.close(); 但conn.close()并没有关闭数据库的物理连接，它仅仅把数据库连接释放，归还给了数据库连接池。</li>
</ul>
</li>
</ul>
<h4 id="8-3-1-C3P0数据库连接池"><a href="#8-3-1-C3P0数据库连接池" class="headerlink" title="8.3.1 C3P0数据库连接池"></a>8.3.1 C3P0数据库连接池</h4><ul>
<li>获取连接方式一</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用C3P0数据库连接池的方式，获取数据库的连接：不推荐</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title function_">getConnection1</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">ComboPooledDataSource</span> <span class="variable">cpds</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ComboPooledDataSource</span>();</span><br><span class="line">	cpds.setDriverClass(<span class="string">&quot;com.mysql.jdbc.Driver&quot;</span>); </span><br><span class="line">	cpds.setJdbcUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>);</span><br><span class="line">	cpds.setUser(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">	cpds.setPassword(<span class="string">&quot;abc123&quot;</span>);</span><br><span class="line">		</span><br><span class="line"><span class="comment">//	cpds.setMaxPoolSize(100);</span></span><br><span class="line">	</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> cpds.getConnection();</span><br><span class="line">	<span class="keyword">return</span> conn;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>获取连接方式二</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用C3P0数据库连接池的配置文件方式，获取数据库的连接：推荐</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="type">DataSource</span> <span class="variable">cpds</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ComboPooledDataSource</span>(<span class="string">&quot;helloc3p0&quot;</span>);</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title function_">getConnection2</span><span class="params">()</span> <span class="keyword">throws</span> SQLException&#123;</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> cpds.getConnection();</span><br><span class="line">	<span class="keyword">return</span> conn;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中，src下的配置文件为：【c3p0-config.xml】</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">c3p0-config</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">named-config</span> <span class="attr">name</span>=<span class="string">&quot;helloc3p0&quot;</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 获取连接的4个基本信息 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;user&quot;</span>&gt;</span>root<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span>&gt;</span>abc123<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;jdbcUrl&quot;</span>&gt;</span>jdbc:mysql:///test<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;driverClass&quot;</span>&gt;</span>com.mysql.jdbc.Driver<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		</span><br><span class="line">		<span class="comment">&lt;!-- 涉及到数据库连接池的管理的相关属性的设置 --&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;acquireIncrement&quot;</span>&gt;</span>5<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 初始化数据库连接池时连接的数量 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;initialPoolSize&quot;</span>&gt;</span>5<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 数据库连接池中的最小的数据库连接数 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;minPoolSize&quot;</span>&gt;</span>5<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 数据库连接池中的最大的数据库连接数 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;maxPoolSize&quot;</span>&gt;</span>10<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- C3P0 数据库连接池可以维护的 Statement 的个数 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;maxStatements&quot;</span>&gt;</span>20<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 每个连接同时可以使用的 Statement 对象的个数 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;maxStatementsPerConnection&quot;</span>&gt;</span>5<span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="tag">&lt;/<span class="name">named-config</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">c3p0-config</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="8-3-2-DBCP数据库连接池"><a href="#8-3-2-DBCP数据库连接池" class="headerlink" title="8.3.2 DBCP数据库连接池"></a>8.3.2 DBCP数据库连接池</h4><ul>
<li>DBCP 是 Apache 软件基金组织下的开源连接池实现，该连接池依赖该组织下的另一个开源系统：Common-pool。如需使用该连接池实现，应在系统中增加如下两个 jar 文件：<ul>
<li>Commons-dbcp.jar：连接池的实现</li>
<li>Commons-pool.jar：连接池实现的依赖库</li>
</ul>
</li>
<li><strong>Tomcat 的连接池正是采用该连接池来实现的。</strong>该数据库连接池既可以与应用服务器整合使用，也可由应用程序独立使用。</li>
<li>数据源和数据库连接不同，数据源无需创建多个，它是产生数据库连接的工厂，因此整个应用只需要一个数据源即可。</li>
<li>当数据库访问结束后，程序还是像以前一样关闭数据库连接：conn.close(); 但上面的代码并没有关闭数据库的物理连接，它仅仅把数据库连接释放，归还给了数据库连接池。</li>
<li>配置属性说明</li>
</ul>
<div class="table-container">
<table>
<thead>
<tr>
<th>属性</th>
<th>默认值</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>initialSize</td>
<td>0</td>
<td>连接池启动时创建的初始化连接数量</td>
</tr>
<tr>
<td>maxActive</td>
<td>8</td>
<td>连接池中可同时连接的最大的连接数</td>
</tr>
<tr>
<td>maxIdle</td>
<td>8</td>
<td>连接池中最大的空闲的连接数，超过的空闲连接将被释放，如果设置为负数表示不限制</td>
</tr>
<tr>
<td>minIdle</td>
<td>0</td>
<td>连接池中最小的空闲的连接数，低于这个数量会被创建新的连接。该参数越接近maxIdle，性能越好，因为连接的创建和销毁，都是需要消耗资源的；但是不能太大。</td>
</tr>
<tr>
<td>maxWait</td>
<td>无限制</td>
<td>最大等待时间，当没有可用连接时，连接池等待连接释放的最大时间，超过该时间限制会抛出异常，如果设置-1表示无限等待</td>
</tr>
<tr>
<td>poolPreparedStatements</td>
<td>false</td>
<td>开启池的Statement是否prepared</td>
</tr>
<tr>
<td>maxOpenPreparedStatements</td>
<td>无限制</td>
<td>开启池的prepared 后的同时最大连接数</td>
</tr>
<tr>
<td>minEvictableIdleTimeMillis</td>
<td></td>
<td>连接池中连接，在时间段内一直空闲， 被逐出连接池的时间</td>
</tr>
<tr>
<td>removeAbandonedTimeout</td>
<td>300</td>
<td>超过时间限制，回收没有用(废弃)的连接</td>
</tr>
<tr>
<td>removeAbandoned</td>
<td>false</td>
<td>超过removeAbandonedTimeout时间后，是否进 行没用连接（废弃）的回收</td>
</tr>
</tbody>
</table>
</div>
<ul>
<li>获取连接方式一：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title function_">getConnection3</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">	<span class="type">BasicDataSource</span> <span class="variable">source</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BasicDataSource</span>();</span><br><span class="line">		</span><br><span class="line">	source.setDriverClassName(<span class="string">&quot;com.mysql.jdbc.Driver&quot;</span>);</span><br><span class="line">	source.setUrl(<span class="string">&quot;jdbc:mysql:///test&quot;</span>);</span><br><span class="line">	source.setUsername(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">	source.setPassword(<span class="string">&quot;abc123&quot;</span>);</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//</span></span><br><span class="line">	source.setInitialSize(<span class="number">10</span>);</span><br><span class="line">		</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> source.getConnection();</span><br><span class="line">	<span class="keyword">return</span> conn;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>获取连接方式二：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用dbcp数据库连接池的配置文件方式，获取数据库的连接：推荐</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="type">DataSource</span> <span class="variable">source</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line"><span class="keyword">static</span>&#123;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="type">Properties</span> <span class="variable">pros</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">		</span><br><span class="line">		<span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> DBCPTest.class.getClassLoader().getResourceAsStream(<span class="string">&quot;dbcp.properties&quot;</span>);</span><br><span class="line">			</span><br><span class="line">		pros.load(is);</span><br><span class="line">		<span class="comment">//根据提供的BasicDataSourceFactory创建对应的DataSource对象</span></span><br><span class="line">		source = BasicDataSourceFactory.createDataSource(pros);</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;</span><br><span class="line">		</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title function_">getConnection4</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">		</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> source.getConnection();</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> conn;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中，src下的配置文件为：【dbcp.properties】</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">driverClassName</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">url</span>=<span class="string">jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true&amp;useServerPrepStmts=false</span></span><br><span class="line"><span class="attr">username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">password</span>=<span class="string">abc123</span></span><br><span class="line"></span><br><span class="line"><span class="attr">initialSize</span>=<span class="string">10</span></span><br><span class="line"><span class="comment">#...</span></span><br></pre></td></tr></table></figure>
<h4 id="8-3-3-Druid（德鲁伊）数据库连接池"><a href="#8-3-3-Druid（德鲁伊）数据库连接池" class="headerlink" title="8.3.3 Druid（德鲁伊）数据库连接池"></a>8.3.3 Druid（德鲁伊）数据库连接池</h4><p>Druid是阿里巴巴开源平台上一个数据库连接池实现，它结合了C3P0、DBCP、Proxool等DB池的优点，同时加入了日志监控，可以很好的监控DB池连接和SQL的执行情况，可以说是针对监控而生的DB连接池，<strong>可以说是目前最好的连接池之一。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.druid;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.sql.DataSource;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.alibaba.druid.pool.DruidDataSourceFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestDruid</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">		<span class="type">Properties</span> <span class="variable">pro</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();		 pro.load(TestDruid.class.getClassLoader().getResourceAsStream(<span class="string">&quot;druid.properties&quot;</span>));</span><br><span class="line">		<span class="type">DataSource</span> <span class="variable">ds</span> <span class="operator">=</span> DruidDataSourceFactory.createDataSource(pro);</span><br><span class="line">		<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> ds.getConnection();</span><br><span class="line">		System.out.println(conn);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>其中，src下的配置文件为：【druid.properties】</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">url=jdbc:mysql:<span class="comment">//localhost:3306/test?rewriteBatchedStatements=true</span></span><br><span class="line">username=root</span><br><span class="line">password=<span class="number">123456</span></span><br><span class="line">driverClassName=com.mysql.jdbc.Driver</span><br><span class="line"></span><br><span class="line">initialSize=<span class="number">10</span></span><br><span class="line">maxActive=<span class="number">20</span></span><br><span class="line">maxWait=<span class="number">1000</span></span><br><span class="line">filters=wall</span><br></pre></td></tr></table></figure>
<ul>
<li>详细配置参数：</li>
</ul>
<div class="table-container">
<table>
<thead>
<tr>
<th><strong>配置</strong></th>
<th><strong>缺省</strong></th>
<th><strong>说明</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td></td>
<td>配置这个属性的意义在于，如果存在多个数据源，监控的时候可以通过名字来区分开来。   如果没有配置，将会生成一个名字，格式是：”DataSource-” +   System.identityHashCode(this)</td>
</tr>
<tr>
<td>url</td>
<td></td>
<td>连接数据库的url，不同数据库不一样。例如：mysql :   jdbc:mysql://10.20.153.104:3306/druid2      oracle :   jdbc:oracle:thin:@10.20.149.85:1521:ocnauto</td>
</tr>
<tr>
<td>username</td>
<td></td>
<td>连接数据库的用户名</td>
</tr>
<tr>
<td>password</td>
<td></td>
<td>连接数据库的密码。如果你不希望密码直接写在配置文件中，可以使用ConfigFilter。详细看这里：<a target="_blank" rel="noopener" href="https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter">https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter</a></td>
</tr>
<tr>
<td>driverClassName</td>
<td></td>
<td>根据url自动识别   这一项可配可不配，如果不配置druid会根据url自动识别dbType，然后选择相应的driverClassName(建议配置下)</td>
</tr>
<tr>
<td>initialSize</td>
<td>0</td>
<td>初始化时建立物理连接的个数。初始化发生在显示调用init方法，或者第一次getConnection时</td>
</tr>
<tr>
<td>maxActive</td>
<td>8</td>
<td>最大连接池数量</td>
</tr>
<tr>
<td>maxIdle</td>
<td>8</td>
<td>已经不再使用，配置了也没效果</td>
</tr>
<tr>
<td>minIdle</td>
<td></td>
<td>最小连接池数量</td>
</tr>
<tr>
<td>maxWait</td>
<td></td>
<td>获取连接时最大等待时间，单位毫秒。配置了maxWait之后，缺省启用公平锁，并发效率会有所下降，如果需要可以通过配置useUnfairLock属性为true使用非公平锁。</td>
</tr>
<tr>
<td>poolPreparedStatements</td>
<td>false</td>
<td>是否缓存preparedStatement，也就是PSCache。PSCache对支持游标的数据库性能提升巨大，比如说oracle。在mysql下建议关闭。</td>
</tr>
<tr>
<td>maxOpenPreparedStatements</td>
<td>-1</td>
<td>要启用PSCache，必须配置大于0，当大于0时，poolPreparedStatements自动触发修改为true。在Druid中，不会存在Oracle下PSCache占用内存过多的问题，可以把这个数值配置大一些，比如说100</td>
</tr>
<tr>
<td>validationQuery</td>
<td></td>
<td>用来检测连接是否有效的sql，要求是一个查询语句。如果validationQuery为null，testOnBorrow、testOnReturn、testWhileIdle都不会其作用。</td>
</tr>
<tr>
<td>testOnBorrow</td>
<td>true</td>
<td>申请连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能。</td>
</tr>
<tr>
<td>testOnReturn</td>
<td>false</td>
<td>归还连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能</td>
</tr>
<tr>
<td>testWhileIdle</td>
<td>false</td>
<td>建议配置为true，不影响性能，并且保证安全性。申请连接的时候检测，如果空闲时间大于timeBetweenEvictionRunsMillis，执行validationQuery检测连接是否有效。</td>
</tr>
<tr>
<td>timeBetweenEvictionRunsMillis</td>
<td></td>
<td>有两个含义： 1)Destroy线程会检测连接的间隔时间2)testWhileIdle的判断依据，详细看testWhileIdle属性的说明</td>
</tr>
<tr>
<td>numTestsPerEvictionRun</td>
<td></td>
<td>不再使用，一个DruidDataSource只支持一个EvictionRun</td>
</tr>
<tr>
<td>minEvictableIdleTimeMillis</td>
<td></td>
<td></td>
</tr>
<tr>
<td>connectionInitSqls</td>
<td></td>
<td>物理连接初始化的时候执行的sql</td>
</tr>
<tr>
<td>exceptionSorter</td>
<td></td>
<td>根据dbType自动识别   当数据库抛出一些不可恢复的异常时，抛弃连接</td>
</tr>
<tr>
<td>filters</td>
<td></td>
<td>属性类型是字符串，通过别名的方式配置扩展插件，常用的插件有：   监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall</td>
</tr>
<tr>
<td>proxyFilters</td>
<td></td>
<td>类型是List，如果同时配置了filters和proxyFilters，是组合关系，并非替换关系</td>
</tr>
</tbody>
</table>
</div>
<h2 id="第9章：Apache-DBUtils实现CRUD操作"><a href="#第9章：Apache-DBUtils实现CRUD操作" class="headerlink" title="第9章：Apache-DBUtils实现CRUD操作"></a>第9章：Apache-DBUtils实现CRUD操作</h2><h3 id="9-1-Apache-DBUtils简介"><a href="#9-1-Apache-DBUtils简介" class="headerlink" title="9.1 Apache-DBUtils简介"></a>9.1 Apache-DBUtils简介</h3><ul>
<li><p>commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库，它是对JDBC的简单封装，学习成本极低，并且使用dbutils能极大简化jdbc编码的工作量，同时也不会影响程序的性能。</p>
</li>
<li><p>API介绍：</p>
<ul>
<li>org.apache.commons.dbutils.QueryRunner</li>
<li>org.apache.commons.dbutils.ResultSetHandler</li>
<li>工具类：org.apache.commons.dbutils.DbUtils   </li>
</ul>
</li>
<li>API包说明：</li>
</ul>
<h3 id="9-2-主要API的使用"><a href="#9-2-主要API的使用" class="headerlink" title="9.2 主要API的使用"></a>9.2 主要API的使用</h3><h4 id="9-2-1-DbUtils"><a href="#9-2-1-DbUtils" class="headerlink" title="9.2.1 DbUtils"></a>9.2.1 DbUtils</h4><ul>
<li>DbUtils ：提供如关闭连接、装载JDBC驱动程序等常规工作的工具类，里面的所有方法都是静态的。主要方法如下：<ul>
<li><strong>public static void close(…) throws java.sql.SQLException</strong>：　DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL，如果不是的话，它们就关闭Connection、Statement和ResultSet。</li>
<li>public static void closeQuietly(…): 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭，还能隐藏一些在程序中抛出的SQLEeception。</li>
<li>public static void commitAndClose(Connection conn)throws SQLException： 用来提交连接的事务，然后关闭连接</li>
<li>public static void commitAndCloseQuietly(Connection conn)： 用来提交连接，然后关闭连接，并且在关闭连接时不抛出SQL异常。 </li>
<li>public static void rollback(Connection conn)throws SQLException：允许conn为null，因为方法内部做了判断</li>
<li>public static void rollbackAndClose(Connection conn)throws SQLException</li>
<li>rollbackAndCloseQuietly(Connection)</li>
<li>public static boolean loadDriver(java.lang.String driverClassName)：这一方装载并注册JDBC驱动程序，如果成功就返回true。使用该方法，你不需要捕捉这个异常ClassNotFoundException。</li>
</ul>
</li>
</ul>
<h4 id="9-2-2-QueryRunner类"><a href="#9-2-2-QueryRunner类" class="headerlink" title="9.2.2 QueryRunner类"></a>9.2.2 QueryRunner类</h4><ul>
<li><p><strong>该类简单化了SQL查询，它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作，能够大大减少编码量。</strong></p>
</li>
<li><p>QueryRunner类提供了两个构造器：</p>
<ul>
<li>默认的构造器</li>
<li>需要一个 javax.sql.DataSource 来作参数的构造器</li>
</ul>
</li>
<li><p>QueryRunner类的主要方法：</p>
<ul>
<li><strong>更新</strong><ul>
<li>public int update(Connection conn, String sql, Object… params) throws SQLException:用来执行一个更新（插入、更新或删除）操作。</li>
<li>……</li>
</ul>
</li>
<li><strong>插入</strong><ul>
<li>public <T> T insert(Connection conn,String sql,ResultSetHandler<T> rsh, Object… params) throws SQLException：只支持INSERT语句，其中 rsh - The handler used to create the result object from the ResultSet of auto-generated keys.  返回值: An object generated by the handler.即自动生成的键值</li>
<li>….</li>
</ul>
</li>
<li><strong>批处理</strong><ul>
<li>public int[] batch(Connection conn,String sql,Object[][] params)throws SQLException： INSERT, UPDATE, or DELETE语句</li>
<li>public <T> T insertBatch(Connection conn,String sql,ResultSetHandler<T> rsh,Object[][] params)throws SQLException：只支持INSERT语句</li>
<li>…..</li>
</ul>
</li>
<li><strong>查询</strong><ul>
<li>public Object query(Connection conn, String sql, ResultSetHandler rsh,Object… params) throws SQLException：执行一个查询操作，在这个查询中，对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。</li>
<li>…… </li>
</ul>
</li>
</ul>
</li>
<li><p>测试</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 测试添加</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testInsert</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">	<span class="type">QueryRunner</span> <span class="variable">runner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection3();</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;insert into customers(name,email,birth)values(?,?,?)&quot;</span>;</span><br><span class="line">	<span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> runner.update(conn, sql, <span class="string">&quot;何成飞&quot;</span>, <span class="string">&quot;he@qq.com&quot;</span>, <span class="string">&quot;1992-09-08&quot;</span>);</span><br><span class="line"></span><br><span class="line">	System.out.println(<span class="string">&quot;添加了&quot;</span> + count + <span class="string">&quot;条记录&quot;</span>);</span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 测试删除</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testDelete</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">	<span class="type">QueryRunner</span> <span class="variable">runner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection3();</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;delete from customers where id &lt; ?&quot;</span>;</span><br><span class="line">	<span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> runner.update(conn, sql,<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line">	System.out.println(<span class="string">&quot;删除了&quot;</span> + count + <span class="string">&quot;条记录&quot;</span>);</span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="9-2-3-ResultSetHandler接口及实现类"><a href="#9-2-3-ResultSetHandler接口及实现类" class="headerlink" title="9.2.3 ResultSetHandler接口及实现类"></a>9.2.3 ResultSetHandler接口及实现类</h4><ul>
<li><p>该接口用于处理 java.sql.ResultSet，将数据按要求转换为另一种形式。</p>
</li>
<li><p>ResultSetHandler 接口提供了一个单独的方法：Object handle (java.sql.ResultSet .rs)。</p>
</li>
<li><p>接口的主要实现类：</p>
<ul>
<li>ArrayHandler：把结果集中的第一行数据转成对象数组。</li>
<li>ArrayListHandler：把结果集中的每一行数据都转成一个数组，再存放到List中。</li>
<li><strong>BeanHandler：</strong>将结果集中的第一行数据封装到一个对应的JavaBean实例中。</li>
<li><strong>BeanListHandler：</strong>将结果集中的每一行数据都封装到一个对应的JavaBean实例中，存放到List里。</li>
<li>ColumnListHandler：将结果集中某一列的数据存放到List中。</li>
<li>KeyedHandler(name)：将结果集中的每一行数据都封装到一个Map里，再把这些map再存到一个map里，其key为指定的key。</li>
<li><strong>MapHandler：</strong>将结果集中的第一行数据封装到一个Map里，key是列名，value就是对应的值。</li>
<li><strong>MapListHandler：</strong>将结果集中的每一行数据都封装到一个Map里，然后再存放到List</li>
<li><strong>ScalarHandler：</strong>查询单个值对象</li>
</ul>
</li>
</ul>
<ul>
<li>测试</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 测试查询:查询一条记录</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 使用ResultSetHandler的实现类：BeanHandler</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testQueryInstance</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">QueryRunner</span> <span class="variable">runner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection3();</span><br><span class="line">		</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,name,email,birth from customers where id = ?&quot;</span>;</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//</span></span><br><span class="line">	BeanHandler&lt;Customer&gt; handler = <span class="keyword">new</span> <span class="title class_">BeanHandler</span>&lt;&gt;(Customer.class);</span><br><span class="line">	<span class="type">Customer</span> <span class="variable">customer</span> <span class="operator">=</span> runner.query(conn, sql, handler, <span class="number">23</span>);</span><br><span class="line">	System.out.println(customer);	</span><br><span class="line">	JDBCUtils.closeResource(conn, <span class="literal">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 测试查询:查询多条记录构成的集合</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 使用ResultSetHandler的实现类：BeanListHandler</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testQueryList</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">QueryRunner</span> <span class="variable">runner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection3();</span><br><span class="line">		</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,name,email,birth from customers where id &lt; ?&quot;</span>;</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//</span></span><br><span class="line">	BeanListHandler&lt;Customer&gt; handler = <span class="keyword">new</span> <span class="title class_">BeanListHandler</span>&lt;&gt;(Customer.class);</span><br><span class="line">	List&lt;Customer&gt; list = runner.query(conn, sql, handler, <span class="number">23</span>);</span><br><span class="line">	list.forEach(System.out::println);</span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, <span class="literal">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 自定义ResultSetHandler的实现类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testQueryInstance1</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">QueryRunner</span> <span class="variable">runner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection3();</span><br><span class="line">		</span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select id,name,email,birth from customers where id = ?&quot;</span>;</span><br><span class="line">		</span><br><span class="line">	ResultSetHandler&lt;Customer&gt; handler = <span class="keyword">new</span> <span class="title class_">ResultSetHandler</span>&lt;Customer&gt;() &#123;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="keyword">public</span> Customer <span class="title function_">handle</span><span class="params">(ResultSet rs)</span> <span class="keyword">throws</span> SQLException &#123;</span><br><span class="line">			System.out.println(<span class="string">&quot;handle&quot;</span>);</span><br><span class="line"><span class="comment">//			return new Customer(1,&quot;Tom&quot;,&quot;tom@126.com&quot;,new Date(123323432L));</span></span><br><span class="line">				</span><br><span class="line">			<span class="keyword">if</span>(rs.next())&#123;</span><br><span class="line">				<span class="type">int</span> <span class="variable">id</span> <span class="operator">=</span> rs.getInt(<span class="string">&quot;id&quot;</span>);</span><br><span class="line">				<span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> rs.getString(<span class="string">&quot;name&quot;</span>);</span><br><span class="line">				<span class="type">String</span> <span class="variable">email</span> <span class="operator">=</span> rs.getString(<span class="string">&quot;email&quot;</span>);</span><br><span class="line">				<span class="type">Date</span> <span class="variable">birth</span> <span class="operator">=</span> rs.getDate(<span class="string">&quot;birth&quot;</span>);</span><br><span class="line">					</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Customer</span>(id, name, email, birth);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">				</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;;</span><br><span class="line">		</span><br><span class="line">	<span class="type">Customer</span> <span class="variable">customer</span> <span class="operator">=</span> runner.query(conn, sql, handler, <span class="number">23</span>);</span><br><span class="line">		</span><br><span class="line">	System.out.println(customer);</span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, <span class="literal">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 如何查询类似于最大的，最小的，平均的，总和，个数相关的数据，</span></span><br><span class="line"><span class="comment"> * 使用ScalarHandler</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testQueryValue</span><span class="params">()</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">	<span class="type">QueryRunner</span> <span class="variable">runner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryRunner</span>();</span><br><span class="line"></span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> JDBCUtils.getConnection3();</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//测试一：</span></span><br><span class="line"><span class="comment">//	String sql = &quot;select count(*) from customers where id &lt; ?&quot;;</span></span><br><span class="line"><span class="comment">//	ScalarHandler handler = new ScalarHandler();</span></span><br><span class="line"><span class="comment">//	long count = (long) runner.query(conn, sql, handler, 20);</span></span><br><span class="line"><span class="comment">//	System.out.println(count);</span></span><br><span class="line">		</span><br><span class="line">	<span class="comment">//测试二：</span></span><br><span class="line">	<span class="type">String</span> <span class="variable">sql</span> <span class="operator">=</span> <span class="string">&quot;select max(birth) from customers&quot;</span>;</span><br><span class="line">	<span class="type">ScalarHandler</span> <span class="variable">handler</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ScalarHandler</span>();</span><br><span class="line">	<span class="type">Date</span> <span class="variable">birth</span> <span class="operator">=</span> (Date) runner.query(conn, sql, handler);</span><br><span class="line">	System.out.println(birth);</span><br><span class="line">		</span><br><span class="line">	JDBCUtils.closeResource(conn, <span class="literal">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="JDBC总结"><a href="#JDBC总结" class="headerlink" title="JDBC总结"></a>JDBC总结</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">总结</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testUpdateWithTx</span><span class="params">()</span> &#123;</span><br><span class="line">		</span><br><span class="line">	<span class="type">Connection</span> <span class="variable">conn</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">//1.获取连接的操作（</span></span><br><span class="line">		<span class="comment">//① 手写的连接：JDBCUtils.getConnection();</span></span><br><span class="line">		<span class="comment">//② 使用数据库连接池：C3P0;DBCP;Druid</span></span><br><span class="line">		<span class="comment">//2.对数据表进行一系列CRUD操作</span></span><br><span class="line">		<span class="comment">//① 使用PreparedStatement实现通用的增删改、查询操作（version 1.0 \ version 2.0)</span></span><br><span class="line"><span class="comment">//version2.0的增删改public void update(Connection conn,String sql,Object ... args)&#123;&#125;</span></span><br><span class="line"><span class="comment">//version2.0的查询 public &lt;T&gt; T getInstance(Connection conn,Class&lt;T&gt; clazz,String sql,Object ... args)&#123;&#125;</span></span><br><span class="line">		<span class="comment">//② 使用dbutils提供的jar包中提供的QueryRunner类</span></span><br><span class="line">			</span><br><span class="line">		<span class="comment">//提交数据</span></span><br><span class="line">		conn.commit();</span><br><span class="line">			</span><br><span class="line">	</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">			</span><br><span class="line">			</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">//回滚数据</span></span><br><span class="line">			conn.rollback();</span><br><span class="line">		&#125; <span class="keyword">catch</span> (SQLException e1) &#123;</span><br><span class="line">			e1.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">			</span><br><span class="line">	&#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">		<span class="comment">//3.关闭连接等操作</span></span><br><span class="line">		<span class="comment">//① JDBCUtils.closeResource();</span></span><br><span class="line">		<span class="comment">//② 使用dbutils提供的jar包中提供的DbUtils类提供了关闭的相关操作</span></span><br><span class="line">			</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>JDBC</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://www.naste.top:1024/posts/2414116852.html">https://www.naste.top:1024/posts/2414116852.html</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>XiaoFei🥝</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2022-06-09</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2024-04-26</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>Java</a><a class="post-meta__tags" href="/tags/JDBC/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>JDBC</a><a class="post-meta__tags" href="/tags/MySQL/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>MySQL</a></div></div><link rel="stylesheet" href="/css/coin.css" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">投喂作者</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://www.naste.top:9000/images/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://www.naste.top:9000/images/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><audio id="coinAudio" src="https://npm.elemecdn.com/akilar-candyassets@1.0.36/audio/aowu.m4a"></audio><script defer="defer" src="/js/coin.js"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/posts/2920256992.html"><img class="prev-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743781.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">SpringMVC</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/2343814370.html" title="SpringBoot使用ShardingSphere"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912183.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot使用ShardingSphere</div></div></a></div><div><a href="/posts/2621695512.html" title="Java8新特性-lambda表达式"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1669778330.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">Java8新特性-lambda表达式</div></div></a></div><div><a href="/posts/134766740.html" title="MyBatisPlus"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743782.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MyBatisPlus</div></div></a></div><div><a href="/posts/469711973.html" title="MyBatis"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743770.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MyBatis</div></div></a></div><div><a href="/posts/2176751652.html" title="Spring+SpringMVC+MyBatis"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882681.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">Spring+SpringMVC+MyBatis</div></div></a></div><div><a href="/posts/1412077587.html" title="Spring注解驱动开发"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743803.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">Spring注解驱动开发</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><svg class="meta_icon" style="width:22px;height:22px;position:relative;top:5px"><use xlink:href="#icon-mulu1"></use></svg><span style="font-weight:bold">目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JDBC%E6%A0%B8%E5%BF%83%E6%8A%80%E6%9C%AF"><span class="toc-text">JDBC核心技术</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC1%E7%AB%A0%EF%BC%9AJDBC%E6%A6%82%E8%BF%B0"><span class="toc-text">第1章：JDBC概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E6%95%B0%E6%8D%AE%E7%9A%84%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-text">1.1 数据的持久化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-Java%E4%B8%AD%E7%9A%84%E6%95%B0%E6%8D%AE%E5%AD%98%E5%82%A8%E6%8A%80%E6%9C%AF"><span class="toc-text">1.2 Java中的数据存储技术</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-JDBC%E4%BB%8B%E7%BB%8D"><span class="toc-text">1.3 JDBC介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-JDBC%E4%BD%93%E7%B3%BB%E7%BB%93%E6%9E%84"><span class="toc-text">1.4 JDBC体系结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-JDBC%E7%A8%8B%E5%BA%8F%E7%BC%96%E5%86%99%E6%AD%A5%E9%AA%A4"><span class="toc-text">1.5 JDBC程序编写步骤</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC2%E7%AB%A0%EF%BC%9A%E8%8E%B7%E5%8F%96%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5"><span class="toc-text">第2章：获取数据库连接</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E8%A6%81%E7%B4%A0%E4%B8%80%EF%BC%9ADriver%E6%8E%A5%E5%8F%A3%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-text">2.1 要素一：Driver接口实现类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1-1-Driver%E6%8E%A5%E5%8F%A3%E4%BB%8B%E7%BB%8D"><span class="toc-text">2.1.1 Driver接口介绍</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1-2-%E5%8A%A0%E8%BD%BD%E4%B8%8E%E6%B3%A8%E5%86%8CJDBC%E9%A9%B1%E5%8A%A8"><span class="toc-text">2.1.2 加载与注册JDBC驱动</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E8%A6%81%E7%B4%A0%E4%BA%8C%EF%BC%9AURL"><span class="toc-text">2.2 要素二：URL</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E8%A6%81%E7%B4%A0%E4%B8%89%EF%BC%9A%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81"><span class="toc-text">2.3 要素三：用户名和密码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%96%B9%E5%BC%8F%E4%B8%BE%E4%BE%8B"><span class="toc-text">2.4 数据库连接方式举例</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-1-%E8%BF%9E%E6%8E%A5%E6%96%B9%E5%BC%8F%E4%B8%80"><span class="toc-text">2.4.1 连接方式一</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-2-%E8%BF%9E%E6%8E%A5%E6%96%B9%E5%BC%8F%E4%BA%8C"><span class="toc-text">2.4.2 连接方式二</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-3-%E8%BF%9E%E6%8E%A5%E6%96%B9%E5%BC%8F%E4%B8%89"><span class="toc-text">2.4.3 连接方式三</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-4-%E8%BF%9E%E6%8E%A5%E6%96%B9%E5%BC%8F%E5%9B%9B"><span class="toc-text">2.4.4 连接方式四</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-5-%E8%BF%9E%E6%8E%A5%E6%96%B9%E5%BC%8F%E4%BA%94-%E6%9C%80%E7%BB%88%E7%89%88"><span class="toc-text">2.4.5 连接方式五(最终版)</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC3%E7%AB%A0%EF%BC%9A%E4%BD%BF%E7%94%A8PreparedStatement%E5%AE%9E%E7%8E%B0CRUD%E6%93%8D%E4%BD%9C"><span class="toc-text">第3章：使用PreparedStatement实现CRUD操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E6%93%8D%E4%BD%9C%E5%92%8C%E8%AE%BF%E9%97%AE%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-text">3.1 操作和访问数据库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E4%BD%BF%E7%94%A8Statement%E6%93%8D%E4%BD%9C%E6%95%B0%E6%8D%AE%E8%A1%A8%E7%9A%84%E5%BC%8A%E7%AB%AF"><span class="toc-text">3.2 使用Statement操作数据表的弊端</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-PreparedStatement%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">3.3 PreparedStatement的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-1-PreparedStatement%E4%BB%8B%E7%BB%8D"><span class="toc-text">3.3.1 PreparedStatement介绍</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-2-PreparedStatement-vs-Statement"><span class="toc-text">3.3.2 PreparedStatement vs Statement</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-3-Java%E4%B8%8ESQL%E5%AF%B9%E5%BA%94%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E8%A1%A8"><span class="toc-text">3.3.3 Java与SQL对应数据类型转换表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-4-%E4%BD%BF%E7%94%A8PreparedStatement%E5%AE%9E%E7%8E%B0%E5%A2%9E%E3%80%81%E5%88%A0%E3%80%81%E6%94%B9%E6%93%8D%E4%BD%9C"><span class="toc-text">3.3.4 使用PreparedStatement实现增、删、改操作</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-5-%E4%BD%BF%E7%94%A8PreparedStatement%E5%AE%9E%E7%8E%B0%E6%9F%A5%E8%AF%A2%E6%93%8D%E4%BD%9C"><span class="toc-text">3.3.5 使用PreparedStatement实现查询操作</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-ResultSet%E4%B8%8EResultSetMetaData"><span class="toc-text">3.4 ResultSet与ResultSetMetaData</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4-1-ResultSet"><span class="toc-text">3.4.1 ResultSet</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4-2-ResultSetMetaData"><span class="toc-text">3.4.2 ResultSetMetaData</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-%E8%B5%84%E6%BA%90%E7%9A%84%E9%87%8A%E6%94%BE"><span class="toc-text">3.5 资源的释放</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-6-JDBC-API%E5%B0%8F%E7%BB%93"><span class="toc-text">3.6 JDBC API小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AB%A0%E8%8A%82%E7%BB%83%E4%B9%A0"><span class="toc-text">章节练习</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC4%E7%AB%A0-%E6%93%8D%E4%BD%9CBLOB%E7%B1%BB%E5%9E%8B%E5%AD%97%E6%AE%B5"><span class="toc-text">第4章 操作BLOB类型字段</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-MySQL-BLOB%E7%B1%BB%E5%9E%8B"><span class="toc-text">4.1 MySQL BLOB类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E5%90%91%E6%95%B0%E6%8D%AE%E8%A1%A8%E4%B8%AD%E6%8F%92%E5%85%A5%E5%A4%A7%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-text">4.2 向数据表中插入大数据类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-%E4%BF%AE%E6%94%B9%E6%95%B0%E6%8D%AE%E8%A1%A8%E4%B8%AD%E7%9A%84Blob%E7%B1%BB%E5%9E%8B%E5%AD%97%E6%AE%B5"><span class="toc-text">4.3 修改数据表中的Blob类型字段</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-%E4%BB%8E%E6%95%B0%E6%8D%AE%E8%A1%A8%E4%B8%AD%E8%AF%BB%E5%8F%96%E5%A4%A7%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-text">4.4 从数据表中读取大数据类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC5%E7%AB%A0-%E6%89%B9%E9%87%8F%E6%8F%92%E5%85%A5"><span class="toc-text">第5章 批量插入</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-%E6%89%B9%E9%87%8F%E6%89%A7%E8%A1%8CSQL%E8%AF%AD%E5%8F%A5"><span class="toc-text">5.1 批量执行SQL语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-%E9%AB%98%E6%95%88%E7%9A%84%E6%89%B9%E9%87%8F%E6%8F%92%E5%85%A5"><span class="toc-text">5.2 高效的批量插入</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#5-2-1-%E5%AE%9E%E7%8E%B0%E5%B1%82%E6%AC%A1%E4%B8%80%EF%BC%9A%E4%BD%BF%E7%94%A8Statement"><span class="toc-text">5.2.1 实现层次一：使用Statement</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5-2-2-%E5%AE%9E%E7%8E%B0%E5%B1%82%E6%AC%A1%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8PreparedStatement"><span class="toc-text">5.2.2 实现层次二：使用PreparedStatement</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5-2-3-%E5%AE%9E%E7%8E%B0%E5%B1%82%E6%AC%A1%E4%B8%89"><span class="toc-text">5.2.3 实现层次三</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5-2-4-%E5%AE%9E%E7%8E%B0%E5%B1%82%E6%AC%A1%E5%9B%9B"><span class="toc-text">5.2.4 实现层次四</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC6%E7%AB%A0%EF%BC%9A-%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BA%8B%E5%8A%A1"><span class="toc-text">第6章： 数据库事务</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BA%8B%E5%8A%A1%E4%BB%8B%E7%BB%8D"><span class="toc-text">6.1 数据库事务介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-JDBC%E4%BA%8B%E5%8A%A1%E5%A4%84%E7%90%86"><span class="toc-text">6.2 JDBC事务处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-%E4%BA%8B%E5%8A%A1%E7%9A%84ACID%E5%B1%9E%E6%80%A7"><span class="toc-text">6.3 事务的ACID属性</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-1-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9A%84%E5%B9%B6%E5%8F%91%E9%97%AE%E9%A2%98"><span class="toc-text">6.3.1 数据库的并发问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-2-%E5%9B%9B%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB"><span class="toc-text">6.3.2 四种隔离级别</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-3-%E5%9C%A8MySql%E4%B8%AD%E8%AE%BE%E7%BD%AE%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB"><span class="toc-text">6.3.3 在MySql中设置隔离级别</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC7%E7%AB%A0%EF%BC%9ADAO%E5%8F%8A%E7%9B%B8%E5%85%B3%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-text">第7章：DAO及相关实现类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90BaseDAO-java%E3%80%91"><span class="toc-text">【BaseDAO.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90BookDAO-java%E3%80%91"><span class="toc-text">【BookDAO.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90UserDAO-java%E3%80%91"><span class="toc-text">【UserDAO.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90BookDaoImpl-java%E3%80%91"><span class="toc-text">【BookDaoImpl.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90UserDaoImpl-java%E3%80%91"><span class="toc-text">【UserDaoImpl.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90Book-java%E3%80%91"><span class="toc-text">【Book.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90Page-java%E3%80%91"><span class="toc-text">【Page.java】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E3%80%90User-java%E3%80%91"><span class="toc-text">【User.java】</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC8%E7%AB%A0%EF%BC%9A%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0"><span class="toc-text">第8章：数据库连接池</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-1-JDBC%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0%E7%9A%84%E5%BF%85%E8%A6%81%E6%80%A7"><span class="toc-text">8.1 JDBC数据库连接池的必要性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-2-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0%E6%8A%80%E6%9C%AF"><span class="toc-text">8.2 数据库连接池技术</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-3-%E5%A4%9A%E7%A7%8D%E5%BC%80%E6%BA%90%E7%9A%84%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0"><span class="toc-text">8.3 多种开源的数据库连接池</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#8-3-1-C3P0%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0"><span class="toc-text">8.3.1 C3P0数据库连接池</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#8-3-2-DBCP%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0"><span class="toc-text">8.3.2 DBCP数据库连接池</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#8-3-3-Druid%EF%BC%88%E5%BE%B7%E9%B2%81%E4%BC%8A%EF%BC%89%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0"><span class="toc-text">8.3.3 Druid（德鲁伊）数据库连接池</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC9%E7%AB%A0%EF%BC%9AApache-DBUtils%E5%AE%9E%E7%8E%B0CRUD%E6%93%8D%E4%BD%9C"><span class="toc-text">第9章：Apache-DBUtils实现CRUD操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#9-1-Apache-DBUtils%E7%AE%80%E4%BB%8B"><span class="toc-text">9.1 Apache-DBUtils简介</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-2-%E4%B8%BB%E8%A6%81API%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">9.2 主要API的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#9-2-1-DbUtils"><span class="toc-text">9.2.1 DbUtils</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-2-2-QueryRunner%E7%B1%BB"><span class="toc-text">9.2.2 QueryRunner类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-2-3-ResultSetHandler%E6%8E%A5%E5%8F%A3%E5%8F%8A%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-text">9.2.3 ResultSetHandler接口及实现类</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JDBC%E6%80%BB%E7%BB%93"><span class="toc-text">JDBC总结</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-color: transparent;"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">格言🧬</p><div class="bg-ad"><div>再看看那个光点，它就在这里，这是家园，这是我们 —— 你所爱的每一个人，你认识的一个人，你听说过的每一个人，曾经有过的每一个人，都在它上面度过他们的一生✨</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://stellarium.org/">点击开启星辰之旅</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">猜你想看💡</p><ul class="ft-links"><li><a href="/posts/eec9786.html">魔改指南</a><a href="/box/nav/">网址导航</a></li><li><a href="/social/link/">我的朋友</a><a href="/comments/">留点什么</a></li><li><a href="/personal/about/">关于作者</a><a href="/archives/">文章归档</a></li><li><a href="/categories/">文章分类</a><a href="/tags/">文章标签</a></li><li><a href="/box/Gallery/">我的画廊</a><a href="/personal/bb/">我的唠叨</a></li><li><a href="/site/time/">建设进程</a><a href="/site/census/">网站统计</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链⌛</p><div class="ft-img-group"><div class="img-group-item"><a href="https://www.naste.top:1024/" title="XiaoFei🥝"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div></div></div></div><div class="copyright"><span><b>&copy;2022-2024</b></span><span><b>&nbsp;&nbsp;By XiaoFei🥝</b></span></div><div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" title="博客框架为Hexo_v6.3.0"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Frame-Hexo-blue.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" title="主题版本Butterfly_v4.3.1"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Theme-Butterfly-6513df.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://vercel.com/" style="margin-inline:5px" title="本站采用多线部署，主线路托管于Vercel"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Hosted-Vercel-brightgreen.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://user.51.la/" style="margin-inline:5px" title="本站数据分析得益于51la技术支持"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Analytics-51la-3db1eb.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" style="margin-inline:5px" title="本网站源码由Github提供存储仓库"><img src= "" data-lazy-src=" https://static.naste.top:1024/svg/blog/Source-Github-d021d6.svg" alt=""/></a></p></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><a class="icon-V hidden" onclick="switchNightMode()" title="浅色和深色模式转换"><svg width="25" height="25" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon"></use></svg></a><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button class="share" type="button" title="右键模式" onclick="changeMouseMode()"><i class="fas fa-mouse"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog right_side"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button class="share" type="button" title="分享链接" onclick="share()"><i class="fas fa-share-nodes"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i><span id="percent">0<span>%</span></span></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div class="js-pjax" id="rightMenu"><div class="rightMenu-group rightMenu-small"><a class="rightMenu-item" href="javascript:window.history.back();"><i class="fa fa-arrow-left"></i></a><a class="rightMenu-item" href="javascript:window.history.forward();"><i class="fa fa-arrow-right"></i></a><a class="rightMenu-item" href="javascript:window.location.reload();"><i class="fa fa-refresh"></i></a><a class="rightMenu-item" href="javascript:rmf.scrollToTop();"><i class="fa fa-arrow-up"></i></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-text"><a class="rightMenu-item" href="javascript:rmf.copySelect();"><i class="fa fa-copy"></i><span>复制</span></a><a class="rightMenu-item" href="javascript:window.open(&quot;https://www.baidu.com/s?wd=&quot;+window.getSelection().toString());window.location.reload();"><i class="fa fa-search"></i><span>百度搜索</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-too"><a class="rightMenu-item" href="javascript:window.open(window.getSelection().toString());window.location.reload();"><i class="fa fa-link"></i><span>转到链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-paste"><a class="rightMenu-item" href="javascript:rmf.paste()"><i class="fa fa-copy"></i><span>粘贴</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-post"><a class="rightMenu-item" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item" href="javascript:rmf.copyWordsLink()"><i class="fa fa-link"></i><span>复制本文地址</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-to"><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>新窗口打开</span></a><a class="rightMenu-item" id="menu-too" href="javascript:rmf.open()"><i class="fa fa-link"></i><span>转到链接</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-img"><a class="rightMenu-item" href="javascript:rmf.saveAs()"><i class="fa fa-download"></i><span>保存图片</span></a><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>在新窗口打开</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制图片链接</span></a></div><div class="rightMenu-group rightMenu-line"><a class="rightMenu-item" href="javascript:randomPost()"><i class="fa fa-paper-plane"></i><span>随便逛逛</span></a><a class="rightMenu-item" href="javascript:switchNightMode();"><i class="fa fa-moon"></i><span>昼夜切换</span></a><a class="rightMenu-item" href="/personal/about/"><i class="fa fa-info-circle"></i><span>关于博客</span></a><a class="rightMenu-item" href="javascript:toggleWinbox();"><i class="fas fa-cog"></i><span>美化设置</span></a><a class="rightMenu-item" href="javascript:rmf.fullScreen();"><i class="fas fa-expand"></i><span>切换全屏</span></a><a class="rightMenu-item" href="javascript:window.print();"><i class="fa-solid fa-print"></i><span>打印页面</span></a></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/instant.page/5.1.0/instantpage.min.js" type="module"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdnjs.cloudflare.com/ajax/libs/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);
document.getElementById('loading-box').addEventListener('click',()=> {preloader.endLoading()})</script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: '',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: '',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.staticfile.org/twikoo/1.6.8/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async src="https://cdn1.tianli0.top/npm/vue@2.6.14/dist/vue.min.js"></script><script async src="https://cdn1.tianli0.top/npm/element-ui@2.15.6/lib/index.js"></script><script async src="https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script><script defer type="text/javascript" src="https://cdn1.tianli0.top/npm/sweetalert2@8.19.0/dist/sweetalert2.all.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer src="https://cdn1.tianli0.top/gh/nextapps-de/winbox/dist/winbox.bundle.min.js"></script><script async src="//at.alicdn.com/t/c/font_3586335_hsivh70x0fm.js"></script><script async src="//at.alicdn.com/t/c/font_3636804_gr02jmjr3y9.js"></script><script async src="//at.alicdn.com/t/c/font_3612150_kfv55xn3u2g.js"></script><script async src="https://cdn.wpon.cn/2022-sucai/Gold-ingot.js"></script><canvas id="universe"></canvas><canvas id="snow"></canvas><script defer src="/js/fomal.js"></script><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.js"></script><script src="https://cdn1.tianli0.top/npm/js-heo@1.0.12/metingjs/Meting.min.js"></script><script src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show","#web_bg",".js-pjax","#bibi","body > title","#app","#tag-echarts","#posts-echart","#categories-echarts"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet"><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Java/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍡 XiaoFeiのJava学习笔记 (55)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Linux/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍼 XiaoFeiのLinux笔记 (33)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Python/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍉 XiaoFeiのPython笔记 (2)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/前端/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍟 XiaoFeiの前端笔记 (17)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Other/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍥 XiaoFeiのOther笔记 (10)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item" style="visibility: hidden"></div><a class="magnet_link_more"  href="https://www.naste.top:1024/categories/" style="flex:1;text-align: center;margin-bottom: 10px;">查看更多...</a></div></div>';
    console.log('已挂载magnet')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script><style>#catalog_magnet{flex-wrap: wrap;display: flex;width:100%;justify-content:space-between;padding: 10px 10px 0 10px;align-content: flex-start;}.magnet_item{flex-basis: calc(33.333333333333336% - 5px);background: #e9e9e9;margin-bottom: 10px;border-radius: 8px;transition: all 0.2s ease-in-out;}.magnet_item:hover{background: var(--text-bg-hover)}.magnet_link_more{color:#555}.magnet_link{color:black}.magnet_link:hover{color:white}@media screen and (max-width: 600px) {.magnet_item {flex-basis: 100%;}}.magnet_link_context{display:flex;padding: 10px;font-size:16px;transition: all 0.2s ease-in-out;}.magnet_link_context:hover{padding: 10px 20px;}</style>
    <style></style><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912191.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-08</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</a><div class="blog-slider__text">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672933.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-15</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">Hexo中Markdown语法与外挂标签写法汇总</a><div class="blog-slider__text">Hexo中Markdown语法与外挂标签写法汇总</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 320px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/personal/about/'|| '/personal/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.naste.top/api?xiao-i-fei",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'xiao-i-fei')
    }
  </script><!-- hexo injector body_end end --></body></html>